Skip to content

Optimization Passes List

This is an automatically generated list of all optimization passes available with the default opt_main. This is generated automatically based on comments in the header files.

Note

Additional development passes are available listed here.

If the opt level is set below 'Min opt level' the pass will act as a no-op.

If the opt level is set above 'Cap opt level' the pass (or passes within the compound pass) will be executed with the opt level capped to the specified value.

Warning

Many of these passes have descriptions generated by the Gemini LLM and may not accurately reflect the behavior of the passes. As time goes on manual verification or editing of the pass descriptions may be done to improve accuracy.

default_pipeline - The default pipeline.

Text-proto

Invoked Passes

arith_simp - Arithmetic Simplifications

This pass performs various arithmetic optimizations such as replacement of divide by a constant with non-divide operations.

Note

What follows was generated by the Gemini LLM. Not human verified.

The ArithSimplificationPass applies a wide range of local and algebraic transformations to simplify arithmetic, shift, decode, and comparison expressions in XLS IR. It uses a UnionQueryEngine combining StatelessQueryEngine and a cached PartialInfoQueryEngine to inspect known constant values, bit patterns, and value intervals, visiting nodes in reverse topological order and iterating to a fixed point until no further simplifications apply.

Key optimizations performed by this pass include:

  1. Division and Modulo Optimizations: * Division by Power of Two: udiv(x, 2^K) is replaced by resizing x and shifting right logically (shrl(x, K)). Signed division sdiv(x, +/- 2^L) is replaced with arithmetic and logical right shifts plus a sign-bias addition ((x + ((x >> (L - 1)) >>> (N - L))) >> L, negated if the divisor is negative) to round toward zero. * Division by Non-Power-of-Two Constant: udiv(x, K) and sdiv(x, K) (where K != 0) are strength-reduced into "magic number" multiplication and shifts (following Granlund and Montgomery's algorithm for division by invariant integers). * Division with Small Constant Dividend: udiv(K, x) and sdiv(K, x) where |K| <= 4095 are replaced with a compressed lookup table combining a direct array_index table (for small divisors up to 64) and a priority_sel over cutoff comparisons for larger divisors. * Division by Variable Power of Two or Small Divisor Set (MatchWithLimitedDivisorSpace): When SplitsEnabled(opt_level) is true and udiv or sdiv has a divisor whose IntervalSet has at most kMaxArbitraryDivisorLUTSize (16) possible values (and the dividend is not a known constant with multiple divisor values) or satisfies AtMostOneBitTrue(divisor): if the divisor is a variable power of two (decode(K) or 2^L << K) and satisfies AtMostOneBitTrue(divisor), the division is replaced with variable right shifts (MakePow2ShiftNode); otherwise (when the divisor space has at most 16 values), it is replaced with a priority_sel lookup table (MakeDivLutNode) keyed by eq(divisor, C) over the per-constant strength-reduced divisions. * Division by Shifted Divisor: x / (y << k) is rewritten into (x / y) / (1 << k) (with a division-by-zero guard if needed) when y has enough known leading zeros that y << k cannot overflow. * Modulo by Constant: umod(x, K) and smod(x, K) by 0 or 1 simplify to 0. umod(x, 2^K) extracts the K least-significant bits via bit_slice and zero_ext. smod(x, 2^K) extracts the K low bits and conditionally subtracts 2^K when x < 0 and the remainder is non-zero. Modulo by any other constant K (or with a small constant dividend K % x) is expanded to x - (x / K) * K so the division can be strength-reduced.

  2. Multiplication Optimizations: * Multiply by Zero or Zero-Width Operands: umul/smul by 0, or umul/smul/umulp/smulp with a zero-width operand, are replaced with 0. * Multiply by Positive Power of Two: umul(x, 2^K) and smul(x, 2^K) are replaced by resizing x and left-shifting by K (shll(x, K)). * Multiply by Small Constant (when SplitsEnabled(opt_level) is true, at opt_level >= 3): Multiplication by a positive constant requiring at most one adder/subtractor is decomposed into shifts and an add or sub (e.g., x * 5 becomes (x << 2) + x, and x * 7 becomes (x << 3) - x). * Narrowing Multiplies: If all users of a umul or smul are bit_slice operations that only read the lower W bits, the multiplication itself is narrowed to W bits.

  3. Shift and Extension Optimizations: * Shift by Constant: Shifts by 0 are replaced with the shifted operand. shll(x, K) and shrl(x, K) by a constant K are replaced with a concat of a bit_slice of x and a zero literal (or 0 if K >= width(x)), avoiding a barrel shifter:

      ```
      // Original IR
      amt: bits[8] = literal(value=2)
      ret res: bits[8] = shrl(x, amt)
    
      // Optimized IR
      zero: bits[2] = literal(value=0)
      slice: bits[6] = bit_slice(x, start=2, width=6)
      ret res: bits[8] = concat(zero, slice)
      ```
    

    * Arithmetic Shift Right by Constant: shra(x, K) is replaced with sign_ext(bit_slice(x, ...)). * 1-Bit and Constant-1 Shifts: shll(x: bits[1], amt) and shrl(x: bits[1], amt) become and(x, eq(amt, 0)); shra(x: bits[1], amt) becomes x; and right-shifting a constant 1 becomes zero_ext(eq(amt, 0)). * Power-of-Two Left Shift: (2^K) << N is rewritten as zero_ext(decode(N)) << K. * Strip Redundant Shift Extensions and Clamps: Leading zero concatenations (concat(0, amt)) and upper-bound clamps (LIMIT >= width(x)) on shift amounts are removed. * Collapse Nested Extensions: zero_ext(zero_ext(x)) and sign_ext(sign_ext(x)) are collapsed into a single extension.

  4. Decode and Mask Optimizations: * Small Decodes: A 1-bit wide decode(x) becomes eq(x, 0). A 2-bit wide decode(x: bits[1]) becomes concat(x, not(x)). * Decode Index Cleanup: Strips leading zeros (concat(0, idx)) and redundant upper-bound clamps (LIMIT >= width(decode)) from decode inputs. * Mask Idiom (decode(N) - 1): Rewrites sub(decode(N), 1) and add(decode(N), all_ones) to not(shll(all_ones, N)), eliminating an adder.

  5. Addition and Comparison Optimizations: * Two's Complement Negation: add(not(x), 1) is simplified to neg(x). * Sign-Extended Boolean Addition: add(sign_ext(c: bits[1]), K) is simplified to sel(c, cases=[K, K - 1]). * Inverted Comparisons: not(cmp(x, y)) with a single-use comparison is replaced by the inverse comparison (e.g., uge(x, y) for not(ult(x, y))). * Sign-Bit Comparisons (when NarrowingEnabled(opt_level) is true, at opt_level >= 2): slt(x, 0) is replaced with msb(x) and sge(x, 0) with not(msb(x)). * Unsigned Comparison to LSB Mask (when NarrowingEnabled(opt_level) is true): Unsigned comparisons (ult, ugt, ule, uge) against a constant mask of trailing ones 0...01...1 (or ugt against mask - 1) are reduced to or_reduce, nor_reduce, and and_reduce over the leading and trailing bit slices. * Comparisons with Negation or Bitwise Not: Eliminates single-use neg in signed comparisons (cmp(-lhs, -rhs) and cmp(-expr, K) with xor corrections for MIN_SIGNED), simplifies eq(not(x), K) to eq(x, ~K), and simplifies eq(sel(p, cases=[x, neg(x)]), 0) to eq(x, 0). * Comparison of Injective Operations: Rewrites eq/ne comparisons of X + C0, X - C0, C0 - X, or non-overflowing umul(X, C0) against a constant C1 to directly compare X against the solved constant (or folds impossible umul comparisons to a constant boolean). * Same-Width Modular Equality Cancellation: Simplifies eq and ne comparisons of a 2-operand add, sub, or xor against one of its own operands—(x + y) cmp x, (y + x) cmp x, (x - y) cmp x, (x ^ y) cmp x, or (y ^ x) cmp x—to y cmp 0 (for sub, cancellation applies only when the shared operand x is the minuend).

Header

array_simp - Array Simplification

Pass which simplifies or eliminates some array-type operations such as ArrayIndex.

Note

What follows was generated by the Gemini LLM. Not human verified.

The ArraySimplificationPass simplifies and eliminates array-related operations (array, array_index, array_update, array_slice, and array-typed sel/priority_sel/one_hot_sel) to reduce multiplexer width and eliminate unnecessary array storage. It uses a UnionQueryEngine combining StatelessQueryEngine and LazyTernaryQueryEngine.

The pass executes in three stages:

  1. Clamping Known Out-of-Bounds ArrayIndex Indices: Scans all array_index nodes and clamps any index operand whose minimum unsigned value (MinUnsignedValue) is greater than or equal to the dimension size to a literal size - 1.

  2. Flattening Sequential ArrayUpdate Chains: Walks the graph in reverse topological order to find chains of array_update operations sharing a common index prefix. When the chain updates at least half of the subarray's elements (or at least 2 elements when SplitsEnabled(opt_level) is true, at opt_level >= 3), the chain is collapsed into a single array construction where each element uses a priority_sel over the update indices.

  3. Worklist-Driven Iterative Simplifications: Seeds a worklist in reverse topological order and repeatedly applies local rewrites until reaching a fixed point:

    * ArrayIndex Simplifications: * Empty Indices: array_index(A, {}) is replaced with A. * Unit-Size Dimensions: Any non-literal index into a dimension of size 1 is replaced with 0. * Indexing into Array: If the first index into an array node is constant, extracts the selected operand directly (clamping if out of bounds). If the index is dynamic, replaces the array_index with a sel over the reachable array operands (using the last element as default for clamping):

          ```
          // Original IR
          arr: bits[32][3] = array(a, b, c)
          ret res: bits[32] = array_index(arr, indices=[idx])
    
          // Optimized IR (for idx: bits[2])
          ret res: bits[32] = sel(idx, cases=[a, b], default=c)
          ```
    
      *   **Indexing into `ArrayConcat`**: If the first index is a known
          in-bounds constant, bypasses `array_concat` to index directly
          into the corresponding concatenated array operand.
      *   **Consecutive `ArrayIndex` Operations**: Flattens nested
          `array_index(array_index(A, {i}), {j})` into
          `array_index(A, {i, j})`.
      *   **`ArrayIndex` of Select**: Pushes `array_index` into the cases
          of `sel`, `one_hot_sel`, or `priority_sel` when the select has a
          single user, or when `SplitsEnabled(opt_level)` is true and
          either the array is small (`size <= 3`) or every live user of the
          select is a constant-indexed `array_index`
          (`ArrayOnlyConstIndexed`).
      *   **`ArrayIndex` of `ArrayUpdate`**:
          *   If the update indices match the read indices (or are a prefix
              of them) and the access is known in-bounds, bypasses the
              array to read directly from `update_value` (preserving
              `assumed_in_bounds` when provably in bounds).
          *   If the update and read indices are provably unequal and the
              read is in-bounds, bypasses the `array_update` to read from
              the original array.
          *   For small 1D arrays (`size <= 3`) when
              `SplitsEnabled(opt_level)` is true, unwinds
              `array_index(array_update(A, v, {u_idx}), {r_idx})` into a
              `priority_sel` comparing `u_idx` against the clamped `r_idx`.
    

    * ArrayUpdate Simplifications: * Empty or Redundant Updates: array_update(A, v, {}) becomes v, and array_update(A, array_index(A, {idx}), {idx}) becomes A. * Unit-Size Dimensions: Replaces updates to leading size-1 dimensions with a priority_sel checking whether the indices are 0 (or directly with the wrapped value if assumed in-bounds). * Hoisting ArrayUpdate into Array: When updating a single-use array node and either the first index is constant or SplitsEnabled(opt_level) is true, pushes the update into the compatible elements of the array (inserting priority_sels when the index is not fully known), or unpacks a constant array updated at a constant in-bounds index. * Nested and Overwritten Updates: Merges array_update(A, array_update(array_index(A, {i}), v, {j}), {i}) into array_update(A, v, {i, j}) (preserving assumed_in_bounds when both outer and inner updates are provably in bounds), and removes earlier updates in a single-use chain whose index is overwritten by a later prefix update.

    * Array and ArraySlice Simplifications: * Decompose/Recompose Elimination: Replaces an array built from sequential array_index(A, {prefix..., 0..N-1}) elements with A (or array_index(A, {prefix...})). * Static ArraySlice: Replaces an array_slice with a known constant start index with an array of static array_index operations.

    * Array-Typed Select Simplifications: * Conditional Update Hoisting: Rewrites sel(p, cases=[A, array_update(A, v, {idx})]) into array_update(A, sel(p, cases=[array_index(A, {idx}), v]), {idx}) so the mux operates on a single element rather than the entire array. * Select of Arrays to Array of Selects: When all branches (up to 2) of a select are array nodes, pushes the select element-wise into a single array of narrower selects.

Header

array_untuple - Array UnTuple

Pass which changes any (non-external) array-of-tuple into a tuple-of-arrays. We can see through tuples quite well but can't see through arrays to anywhere near the same extent. Therefore the struct-of-array representation is always superior.

Note that this pass makes no attempt to unpack or repack arrays which escape the function-base. This means that anything which comes in through a function param, or a procs recv or escapes through a function return or a proc send is not untuple'd.

TODO(allight): We could do this at the cost of a significant number of ir nodes. We should experiment to see if this is worth doing.

Note

What follows was generated by the Gemini LLM. Not human verified.

The ArrayUntuplePass transforms internal arrays of tuples (Array<Tuple<A, B, ...>>) into conceptual tuples of component arrays (Array<A>, Array<B>, ...) within functions and procs (blocks are skipped). This struct-of-arrays (SoA) transformation separates independent tuple fields into distinct arrays so that subsequent passes (such as DataflowSimplificationPass, ArraySimplificationPass, and DeadCodeEliminationPass) can optimize or eliminate unused fields independently.

How it Works:

  1. Grouping Connected Array Operations (FindUntupleGroups): Uses a UnionFind<Node*> structure to group nodes that must be transformed together. Connected operations that union their array operands and results into the same equivalence class include array_update, array_slice, array_concat, eq, ne, sel, priority_sel, one_hot_sel, gate, and all state_reads and next_value value operands associated with the same proc StateElement.

  2. Excluding Externally Visible or Unhandled Groups (FindExternalGroups): Identifies equivalence groups that cannot be untupled without repacking: * Function parameters (param) and function return values of array type. * Proc send data operands of array type. * Proc StateElements whose state_reads are only used in no-op self-updates (IsNoOpNext). * Arrays of empty tuples (()[N]). * Nested arrays of arrays of tuples ((A, B)[M][N]). * The update_value operand of an array_update. * Arrays of tuples produced or consumed by any other unhandled operation (such as tuple_index extracting an array from a receive token/data tuple).

  3. Rewriting Eligible Groups (UntupleVisitor): Traverses the graph in topological order and splits each eligible Array<Tuple<T_0, ..., T_{k-1}>> node into k component arrays Array<T_0>, ..., Array<T_{k-1}>: * Literal: Splits an array-of-tuples literal into k separate array literals, one for each tuple element. * StateRead and Next: Splits an array-of-tuples proc StateElement into k new state elements (<name>_tuple_element_i) with corresponding state_read and next_value nodes, detaching the original state element into a dead no-op update. * Array: Extracts tuple elements from each operand via tuple_index and constructs k separate array nodes. * ArrayIndex: Replaces array_index(arr, indices) with a tuple of k array_index nodes indexing into each component array. * ArrayUpdate, ArraySlice, ArrayConcat, Gate, and Selects (Sel, PrioritySel, OneHotSel): Distributes the operation across each of the k component arrays. * Eq and Ne: Compares each pair of component arrays individually and combines the boolean results with and (for eq) or or (for ne).

Example:

// Original IR
fn read_second_field(t0: (bits[32], bits[16]),
                     t1: (bits[32], bits[16]),
                     idx: bits[1]) -> bits[16] {
  arr: (bits[32], bits[16])[2] = array(t0, t1)
  elem: (bits[32], bits[16]) = array_index(arr, indices=[idx])
  ret res: bits[16] = tuple_index(elem, index=1)
}

// After ArrayUntuplePass (and subsequent tuple/dead-code cleanup)
fn read_second_field(t0: (bits[32], bits[16]),
                     t1: (bits[32], bits[16]),
                     idx: bits[1]) -> bits[16] {
  t0_f1: bits[16] = tuple_index(t0, index=1)
  t1_f1: bits[16] = tuple_index(t1, index=1)
  arr_tuple_idx_1: bits[16][2] = array(t0_f1, t1_f1)
  ret elem_tuple_idx_1: bits[16] = array_index(arr_tuple_idx_1,
                                               indices=[idx])
}

Header

basic_simp - Basic Simplifications

This pass does simple pattern-matching optimizations which are ~always a good idea to do (replacing a node with a constant, removing operands of nodes, etc). They improve QoR, do not increase the number of nodes in the graph, preserve the same abstraction level, and do not impede later optimizations via obfuscation. These optimizations require no analyses beyond looking at the node and its operands. Examples include: not(not(x)) => x, x + 0 => x, etc.

Note

What follows was generated by the Gemini LLM. Not human verified.

The BasicSimplificationPass applies fast, local pattern-matching optimizations to the XLS IR using a StatelessQueryEngine. It iteratively transforms nodes in the function or proc until reaching a fixed point, reducing node count and simplifying expressions without increasing graph complexity or obscuring high-level structure.

Key simplifications performed by this pass include:

  1. Select and Control-Flow Simplifications: * priority_sel(bits[0], cases=[], default=X) => X. * Select of Compared Operands: A binary select (sel or priority_sel) whose selector is eq(x, y) or ne(x, y) and whose branches are x and y simplifies directly to x or y (e.g., sel(eq(x, y), cases=[x, y]) => x, and sel(ne(x, y), cases=[x, y]) => y). * Not/Increment Zero-Equivalence: Since both ~x == 0 and x + 1 == 0 hold if and only if x is all ones, (eq|ne)(sel(c, cases=[not(x), add(x, 1)]), 0) (with either operand or branch ordering) is simplified to (eq|ne)(x, all_ones). * Commutative Op on Swapped Selects: For any non-side-effecting commutative binary operation op, op(sel(p, cases=[a, b]), sel(p, cases=[b, a])) is simplified to op(a, b).

  2. Arithmetic Identities and Involutions: * add(x, 0), sub(x, 0), shll(x, 0), shrl(x, 0), and shra(x, 0) => x. * sub(x, x) => 0. * umul(x, 0) and smul(x, 0) => 0. * add(x, not(x)) and add(not(x), x) => all_ones. * neg(neg(x)) => x. * 1-Bit Arithmetic: neg(x: bits[1]) => x and sub(0, x: bits[1]) => x.

  3. Bitwise and N-ary Logical Simplifications: * not(not(x)) => x. * xor(x, all_ones) => not(x). * Single-Operand N-ary Ops: and(x) and or(x) => x; nand(x) and nor(x) => not(x). * Duplicate Operand Removal: Deduplicates repeated operands in and, or, nand, and nor (e.g., and(x, y, x) => and(x, y)). In xor, operands appearing an even number of times cancel out (xor(x, x) => 0) and operands appearing an odd number of times collapse to a single instance (xor(x, x, x) => x). * Identity and Absorbing Constants: Removes 0 operands from or, xor, and nor, and removes all_ones operands from and and nand. Replaces or(..., all_ones, ...) with all_ones, nor(..., all_ones, ...) with 0, and(..., 0, ...) with 0, and nand(..., 0, ...) with all_ones. * Complementary Operands: Replaces and(..., x, ..., not(x), ...) with 0 and or(..., x, ..., not(x), ...) with all_ones. * Flattening Single-Use Associative N-ary Ops: Inlines single-use nested N-ary operations of the same associative opcode into the parent operation:

      ```
      // Original IR
      or.1: bits[8] = or(w, x)
      or.2: bits[8] = or(y, z)
      ret res: bits[8] = or(or.1, or.2)
    
      // Optimized IR (after dead code elimination)
      ret res: bits[8] = or(w, x, y, z)
      ```
    

    * Constant Folding in N-ary Ops: Combines multiple known constant operands in associative and commutative N-ary operations into a single literal operand.

  4. Bitwise Reduction Simplifications: * and_reduce(x), or_reduce(x), and xor_reduce(x) on a 1-bit x => x; on a 0-bit operand => the operation's identity (1 for and_reduce, 0 for or_reduce and xor_reduce). * or_reduce(neg(x)) => or_reduce(x). * Sign-Extension Mask Reduction: For width w > 1 and b: bits[1], rewrites or_reduce(and(x, sign_ext(b, new_bit_count=w))) to and(b, or_reduce(x)) and and_reduce(and(x, sign_ext(b, new_bit_count=w))) to and(b, and_reduce(x)) (and similarly with not(b) when the sign_ext mask is inverted with not).

  5. Comparison Simplifications: * 1-Bit Equality: eq(x: bits[1], 1) => x and eq(x: bits[1], 0) => not(x). * Reflexive and Irreflexive Relations: Replaces eq(x, x), sge(x, x), uge(x, x), sle(x, x), and ule(x, x) with 1; replaces ne(x, x), sgt(x, x), ugt(x, x), slt(x, x), and ult(x, x) with 0. * Zero-Width Comparisons: For zero-width values, eq(x, y) => 1 and ne(x, y) => 0. * Inequality Disjunction: or(ugt(a, b), ult(a, b)) => ne(a, b).

Header

bdd_cse - BDD-based Common Subexpression Elimination

Pass which commons equivalent expressions in the graph using binary decision diagrams.

Note

What follows was generated by the Gemini LLM. Not human verified.

The BddCsePass (BDD-based Common Subexpression Elimination) identifies and merges logically equivalent bits-typed expressions within a function or proc using Binary Decision Diagrams (BDDs). Unlike the purely syntactic CsePass, BddCsePass can detect semantic equivalence across expressions with different IR structures by comparing their canonical BDD representations.

How it Works:

  1. Canonical BDD Representation: The pass queries a shared BddQueryEngine to obtain the BDD node index for every bit of each bits-typed node in the graph. Because reduced ordered BDDs are canonical for a fixed variable ordering, two nodes compute the same Boolean function on every bit if and only if they have the same bit width and identical BDD node indices for all bit positions.

  2. Delay-Aware Topological Ordering (GetNodeOrder): Before comparing nodes, the pass computes each node's critical-path delay from the graph roots using GetStandardDelayEstimator(). Nodes are sorted in monotonically non-decreasing order of critical-path delay, breaking ties by topological sort index. This guarantees a valid topological traversal (preventing cycles) while ensuring that when an earlier node replaces a later node, the replacement never increases the critical-path delay of any path through the graph.

  3. Hash Bucketing and Replacement: The pass iterates through the sorted nodes (skipping non-bits nodes and literals) and hashes the vector of per-bit BDD node indices for each node. Nodes with matching hashes are grouped into buckets and compared bit-by-bit (is_same_value). When a node matches an earlier candidate in the same bucket, all uses of the node are replaced with the earlier candidate.

Example: Two syntactically distinct expressions that compute the same Boolean value will share the same BDD node and be commoned into a single node:

// Original IR
fn compare_twice(x: bits[16]) -> (bits[1], bits[1]) {
  forty_two: bits[16] = literal(value=42)
  x_eq_42: bits[1] = eq(x, forty_two)
  x_ne_42: bits[1] = ne(forty_two, x)
  not_ne: bits[1] = not(x_ne_42)
  ret res: (bits[1], bits[1]) = tuple(x_eq_42, not_ne)
}

// Optimized IR (after BddCsePass and dead code elimination)
fn compare_twice(x: bits[16]) -> (bits[1], bits[1]) {
  forty_two: bits[16] = literal(value=42)
  x_eq_42: bits[1] = eq(x, forty_two)
  ret res: (bits[1], bits[1]) = tuple(x_eq_42, x_eq_42)
}

Header

bdd_simp - BDD-based Simplification

Runs BDD-based simplifications on the function.

Note

What follows was generated by the Gemini LLM. Not human verified.

The BddSimplificationPass leverages Binary Decision Diagrams (BDDs) via a UnionQueryEngine (combining StatelessQueryEngine and BddQueryEngine) to perform logic-level simplifications on the IR in topological order.

The pass performs the following transformations:

  1. Replacing Statically Known Bits with Literals: For each non-literal bits-typed node, the pass inspects known constant bits at the most-significant end (prefix) and least-significant end (suffix): * Fully Known Nodes: If all bits of the node are statically known, the node is replaced with a literal at any optimization level. * Known Prefix/Suffix Splitting (when SplitsEnabled(opt_level) is true, at opt_level >= 3): If a contiguous prefix and/or suffix of bits is constant (and not already exposed as a literal operand of a concat), the node is replaced by a concat of the known prefix literal, a bit_slice of the remaining unknown middle bits, and the known suffix literal.

  2. Removing Redundant Operands in 1-Bit Boolean Operations: For 1-bit and, nand, or, and nor operations with up to 10 operands (kMaxBooleanFanIn), the pass checks whether any operand is logically implied by the others (ImpliedNodeValue). Specifically, for each operand, it assumes all other non-redundant operands take the non-controlling ("ignorable") value (1 for and/nand, 0 for or/nor). If the target operand is guaranteed to also take that non-controlling value under those assumptions, the operand is replaced with the constant 1 or 0 literal:

    // Original IR
    c: bits[1] = and(a, b)
    ret res: bits[1] = and(a, b, c)
    
    // Optimized IR (c is implied to be 1 whenever a == 1 and b == 1)
    one: bits[1] = literal(value=1)
    ret res: bits[1] = and(a, b, one)
    
  3. Replacing Two-Way OneHotSelect with Select (when SplitsEnabled(opt_level) is true, at opt_level >= 3): If a one_hot_sel has a 2-bit selector that BDD analysis proves is strictly one-hot (AtLeastOneBitTrue and AtMostOneBitTrue), it is replaced with a 2-way sel indexed by bit_slice(selector, start=0, width=1) with cases=[case(1), case(0)].

  4. Eliminating OneHot on Inputs with at Most One Bit Set: If BDD analysis proves that the operand x of a one_hot node has at most one bit set (AtMostOneBitTrue(x)), the one_hot operation is replaced with concat(eq(x, 0), x).

  5. Narrowing PrioritySelect with Guaranteed Set Bits (when NarrowingEnabled(opt_level) is true, at opt_level >= 2): If BDD analysis proves that at least one bit of a priority_sel selector is always set (AtLeastOneBitTrue), the pass finds the lowest bit index last_bit such that at least one bit in selector[0..last_bit] is guaranteed to be true. It then slices the selector to last_bit bits, retains cases[0..last_bit-1], and promotes case(last_bit) to be the new default value, discarding unreachable higher-index cases and the previous default.

Header

bdd_simp(2) - BDD-based Simplification with opt level <= 2

Runs BDD-based simplifications on the function.

Note

What follows was generated by the Gemini LLM. Not human verified.

The BddSimplificationPass leverages Binary Decision Diagrams (BDDs) via a UnionQueryEngine (combining StatelessQueryEngine and BddQueryEngine) to perform logic-level simplifications on the IR in topological order.

The pass performs the following transformations:

  1. Replacing Statically Known Bits with Literals: For each non-literal bits-typed node, the pass inspects known constant bits at the most-significant end (prefix) and least-significant end (suffix): * Fully Known Nodes: If all bits of the node are statically known, the node is replaced with a literal at any optimization level. * Known Prefix/Suffix Splitting (when SplitsEnabled(opt_level) is true, at opt_level >= 3): If a contiguous prefix and/or suffix of bits is constant (and not already exposed as a literal operand of a concat), the node is replaced by a concat of the known prefix literal, a bit_slice of the remaining unknown middle bits, and the known suffix literal.

  2. Removing Redundant Operands in 1-Bit Boolean Operations: For 1-bit and, nand, or, and nor operations with up to 10 operands (kMaxBooleanFanIn), the pass checks whether any operand is logically implied by the others (ImpliedNodeValue). Specifically, for each operand, it assumes all other non-redundant operands take the non-controlling ("ignorable") value (1 for and/nand, 0 for or/nor). If the target operand is guaranteed to also take that non-controlling value under those assumptions, the operand is replaced with the constant 1 or 0 literal:

    // Original IR
    c: bits[1] = and(a, b)
    ret res: bits[1] = and(a, b, c)
    
    // Optimized IR (c is implied to be 1 whenever a == 1 and b == 1)
    one: bits[1] = literal(value=1)
    ret res: bits[1] = and(a, b, one)
    
  3. Replacing Two-Way OneHotSelect with Select (when SplitsEnabled(opt_level) is true, at opt_level >= 3): If a one_hot_sel has a 2-bit selector that BDD analysis proves is strictly one-hot (AtLeastOneBitTrue and AtMostOneBitTrue), it is replaced with a 2-way sel indexed by bit_slice(selector, start=0, width=1) with cases=[case(1), case(0)].

  4. Eliminating OneHot on Inputs with at Most One Bit Set: If BDD analysis proves that the operand x of a one_hot node has at most one bit set (AtMostOneBitTrue(x)), the one_hot operation is replaced with concat(eq(x, 0), x).

  5. Narrowing PrioritySelect with Guaranteed Set Bits (when NarrowingEnabled(opt_level) is true, at opt_level >= 2): If BDD analysis proves that at least one bit of a priority_sel selector is always set (AtLeastOneBitTrue), the pass finds the lowest bit index last_bit such that at least one bit in selector[0..last_bit] is guaranteed to be true. It then slices the selector to last_bit bits, retains cases[0..last_bit-1], and promotes case(last_bit) to be the new default value, discarding unreachable higher-index cases and the previous default.

Header

bdd_simp(3) - BDD-based Simplification with opt level <= 3

Runs BDD-based simplifications on the function.

Note

What follows was generated by the Gemini LLM. Not human verified.

The BddSimplificationPass leverages Binary Decision Diagrams (BDDs) via a UnionQueryEngine (combining StatelessQueryEngine and BddQueryEngine) to perform logic-level simplifications on the IR in topological order.

The pass performs the following transformations:

  1. Replacing Statically Known Bits with Literals: For each non-literal bits-typed node, the pass inspects known constant bits at the most-significant end (prefix) and least-significant end (suffix): * Fully Known Nodes: If all bits of the node are statically known, the node is replaced with a literal at any optimization level. * Known Prefix/Suffix Splitting (when SplitsEnabled(opt_level) is true, at opt_level >= 3): If a contiguous prefix and/or suffix of bits is constant (and not already exposed as a literal operand of a concat), the node is replaced by a concat of the known prefix literal, a bit_slice of the remaining unknown middle bits, and the known suffix literal.

  2. Removing Redundant Operands in 1-Bit Boolean Operations: For 1-bit and, nand, or, and nor operations with up to 10 operands (kMaxBooleanFanIn), the pass checks whether any operand is logically implied by the others (ImpliedNodeValue). Specifically, for each operand, it assumes all other non-redundant operands take the non-controlling ("ignorable") value (1 for and/nand, 0 for or/nor). If the target operand is guaranteed to also take that non-controlling value under those assumptions, the operand is replaced with the constant 1 or 0 literal:

    // Original IR
    c: bits[1] = and(a, b)
    ret res: bits[1] = and(a, b, c)
    
    // Optimized IR (c is implied to be 1 whenever a == 1 and b == 1)
    one: bits[1] = literal(value=1)
    ret res: bits[1] = and(a, b, one)
    
  3. Replacing Two-Way OneHotSelect with Select (when SplitsEnabled(opt_level) is true, at opt_level >= 3): If a one_hot_sel has a 2-bit selector that BDD analysis proves is strictly one-hot (AtLeastOneBitTrue and AtMostOneBitTrue), it is replaced with a 2-way sel indexed by bit_slice(selector, start=0, width=1) with cases=[case(1), case(0)].

  4. Eliminating OneHot on Inputs with at Most One Bit Set: If BDD analysis proves that the operand x of a one_hot node has at most one bit set (AtMostOneBitTrue(x)), the one_hot operation is replaced with concat(eq(x, 0), x).

  5. Narrowing PrioritySelect with Guaranteed Set Bits (when NarrowingEnabled(opt_level) is true, at opt_level >= 2): If BDD analysis proves that at least one bit of a priority_sel selector is always set (AtLeastOneBitTrue), the pass finds the lowest bit index last_bit such that at least one bit in selector[0..last_bit] is guaranteed to be true. It then slices the selector to last_bit bits, retains cases[0..last_bit-1], and promotes case(last_bit) to be the new default value, discarding unreachable higher-index cases and the previous default.

Header

bitslice_simp - Bit-slice simplification

Pass which simplifies bit-slices. This includes collapsing sequential bit-slices, eliminating degenerate full-width slices, and others.

Note

What follows was generated by the Gemini LLM. Not human verified.

The BitSliceSimplificationPass optimizes bit_slice, dynamic_bit_slice, and bit_slice_update operations in the IR. It combines local pattern matching with a UnionQueryEngine (pairing StatelessQueryEngine with PartialInfoQueryEngine when opt_level >= 3, or LazyTernaryQueryEngine at lower optimization levels).

The pass first visits nodes in reverse topological order to simplify dynamic_bit_slice and bit_slice_update nodes, and then processes all static bit_slice nodes via a worklist until reaching a fixed point:

  1. Simplifying DynamicBitSlice Operations: * Out-of-Bounds Start: If MinUnsignedValue(start) is at least the bit width of to_slice, replaces the slice with a zero literal. * Constant Start Index: Converts a dynamic_bit_slice with a statically known start into a static bit_slice (zero-extending if the slice extends past the MSB of to_slice). * Lifting through Select of Literals: If start is produced by a tree of sel, priority_sel, or one-hot one_hot_sel nodes whose leaves are known constants, lifts the slice into the select tree so each leaf becomes a static bit_slice:

      ```
      // Original IR
      s0: bits[32] = literal(value=5)
      s1: bits[32] = literal(value=25)
      start: bits[32] = sel(p, cases=[s0, s1])
      ret q: bits[16] = dynamic_bit_slice(x, start, width=16)
    
      // Optimized IR
      slice0: bits[16] = bit_slice(x, start=5, width=16)
      slice1: bits[16] = bit_slice(x, start=25, width=16)
      ret q: bits[16] = sel(p, cases=[slice0, slice1])
      ```
    

    * Scaled Start Index: When start is a known multiple of width (either because width is a power of two and start has enough low zero bits, or start is a non-overflowing umul(idx, width)), partitions to_slice into width-bit chunks and replaces the dynamic_bit_slice with a sel indexed by the unscaled idx (with a zero default if out-of-bounds indices are possible).

  2. Simplifying BitSliceUpdate Operations: * Out-of-Bounds Start: If MinUnsignedValue(start) is at least the width of to_update, replaces the operation with to_update. * Constant Start Index: Replaces a bit_slice_update with a known constant start with a concat of bit_slices of to_update and update_value. * Lifting through Select of Literals: If start is a select tree of known constants, lifts the bit_slice_update into the leaves as static concat/bit_slice updates. * Scaled Start Index: When start is a known multiple of the update_value width, slices to_update into an array of chunks, applies array_update using the unscaled index, and flattens the updated elements back into a bit vector with concat.

  3. Simplifying Static BitSlice Operations: * Full-Width Slice: Replaces bit_slice(x, start=0, width=width(x)) with x. * Collapsed Nested Slices: Combines bit_slice(bit_slice(x, s0, w0), s1, w1) into bit_slice(x, s0 + s1, w1). * Hoisting above Concat (when NarrowingEnabled(opt_level) is true, at opt_level >= 2): Rewrites bit_slice(concat(...)) as a concat of only the overlapping operands (slicing boundary operands as needed). * Pushing into Single-Use Bitwise and Low-Bit Arithmetic Operations (when NarrowingEnabled(opt_level) is true): If a bit_slice is the sole user of a bitwise operation, or extracts the low bits (start == 0) of a single-use add, sub, or neg, pushes the bit_slice into the operands so the operation runs at the narrower width. * Hoisting above SignExt (when NarrowingEnabled(opt_level) is true): Simplifies bit_slice(sign_ext(x)) to a direct slice of x (if within x), or for a single-use sign_ext, to a sign_ext of a slice of x's top bits or sign bit. * Narrowing Shifts, Decode, and Selects: When all users of an operation are bit_slices contained within a dominating bit_slice, hoists the slice above shll (when start == 0), shrl/shra (when slicing the MSBs), decode (when start == 0), or sel/priority_sel/one_hot_sel (when NarrowingEnabled(opt_level) is true), and rewrites all sibling slice users to slice from the narrowed operation.

Header

bitwise_recombine - bitwise recombination

Pass which recombines concats of contiguous bit slices & inverted bit slices from a single source node (and constants) into masked bitwise operations.

The pass uses 1D dynamic programming optimal partitioning to balance readability: - Identifies localized sub-runs that can be merged into clean 1-gate masks (nibble-aligned or periodic, e.g. x ^ 0x5555). - Naturally peels boundary constants (e.g. address alignment or padding) to form clean hybrid concats like {x[31:8] ^ 24'h555555, 8'b0}. - Preserves coarse struct/bus layouts where non-aligned hex masks would be unreadable. - Recombines dense bit-salad into 2-gate operations when the splinter count is high.

Recombined operations are composed in NOT -> AND -> XOR -> OR order: - all inverted slices => not(x) - raw and inverted slices => (x ^ mask) - raw slices and 0 literals => (x & mask) - raw slices and 1 literals => (x | mask) - raw slices, 0s, and 1s (no inv) => ((x & mask_and) | mask_or) - inverted and 1s (no raw) => (not(x) | mask_or) - raw, inverted, and 1s => ((x ^ mask_xor) | mask_or) - inverted and 0s (no raw) => (not(x) & mask_and) - raw, inverted, and 0s => ((x & mask_and) ^ mask_xor) - inverted, 0s, and 1s (no raw) => ((not(x) & mask_and) | mask_or) - all four (raw, inv, 0s, 1s) => ((x & mask_and) ^ mask_xor)

This is typically run late in the compiler pipeline (e.g. in codegen 1.5 block cleanup and optimization) to fold un-cancelled bitwise splits back into clean, idiomatic hardware operations before Verilog emission.

Note

What follows was generated by the Gemini LLM. Not human verified.

The BitwiseRecombinationPass acts as a counterpart to BitwiseSimplificationPass and is intended to run after bitwise simplification has finished. While BitwiseSimplificationPass splits masked bitwise operations into concats of bit_slices, literals, and nots to expose bit-level simplification opportunities, any remaining un-cancelled splinters can produce verbose bit-slice concatenations. BitwiseRecombinationPass re-folds contiguous runs of slices and constants back into concise, readable bitwise operations.

How it Works:

  1. Operand Classification (ClassifyOperand): For each concat node, the pass classifies every operand into one of four SliceElementKind categories if possible: * kRaw: bit_slice(x, start, width) or a full bits-typed node x (start = 0). * kInverted: not(bit_slice(x, start, width)), bit_slice(not(x), start, width), or not(x). * kZero: An all-zeros literal of width w. * kOne: An all-ones literal of width w.

  2. Contiguous Run Formation (TryFormRun): A candidate sub-span of concat operands (ordered MSB-to-LSB) forms a valid contiguous run if all non-literal slices reference the same source node x and their bit offsets (with literal widths filling the exact intervening bit ranges) form a contiguous, in-bounds slice of x.

  3. Cost Model and 1D Dynamic Programming (SimplifyConcat): To avoid merging coarse bus fields into unreadable hex masks, the pass evaluates candidate runs with EvaluateSegmentCost: * Mask Periodicity (GetMaskPeriodicity): Masks that are all zeros, nibble-aligned all ones, or periodically repeating at the largest power-of-two period p <= 16 with 2 * p <= hex_width and 2 <= p < width whose virtual top-nibble continuation bits are all zeros are classified as kClean and incur no penalty. Non-nibble-aligned all-ones masks and periodic masks whose virtual top-nibble continuation bits are nonzero are classified as kAlmostClean and incur a flat penalty of 1. Non-periodic (kUnclean) masks incur a readability penalty proportional to their bit width (1 penalty unit per 8 bits). * Gate Costs: Unary not costs 1, each binary mask operation costs 2 plus its mask periodicity penalty, and using two binary masks incurs an extra penalty of 1. * DP Partitioning: A 1D dynamic program finds the minimum-cost partitioning of the concat operands into segments, favoring shorter (unmerged) segments on ties.

  4. Recombination Synthesis (RecombineRun): Each merged segment of length >= 2 is synthesized over a single base bit_slice (or the full source node x) using at most two binary bitwise gates in not -> and -> xor -> or order. When all four element kinds (kRaw, kInverted, kZero, kOne) are present, the and mask clears both kZero and kOne bitfields so the subsequent xor mask can simultaneously invert kInverted bits and set kOne bits without a third gate.

Example:

// Original IR (alternating raw/inverted nibbles with low zero padding)
slice4: bits[4] = bit_slice(x, start=16, width=4)
slice3: bits[4] = bit_slice(x, start=12, width=4)
inv3: bits[4] = not(slice3)
slice2: bits[4] = bit_slice(x, start=8, width=4)
slice1: bits[4] = bit_slice(x, start=4, width=4)
inv1: bits[4] = not(slice1)
z0: bits[4] = literal(value=0)
ret res: bits[20] = concat(slice4, inv3, slice2, inv1, z0)

// Optimized IR (after dead code elimination; peels low zero padding and
// recombines upper 16 bits into periodic XOR)
hi: bits[16] = bit_slice(x, start=4, width=16)
mask: bits[16] = literal(value=0x0f0f)
xored: bits[16] = xor(hi, mask)
z0: bits[4] = literal(value=0)
ret res: bits[20] = concat(xored, z0)

Header

bitwise_simp - bitwise simplification

Pass which simplifies bitwise operations (AND, OR, XOR) with constant masks by transforming them into concats of BitSlices, Literals, and Nots. This optimization is only enabled when SplitsEnabled is true.

Note

What follows was generated by the Gemini LLM. Not human verified.

The BitwiseSimplificationPass simplifies and, or, and xor operations using per-bit ternary knowledge from a UnionQueryEngine (combining StatelessQueryEngine and PartialInfoQueryEngine).

How it Works:

  1. Full Constant Folding and Inversion (All Optimization Levels): * If the query engine determines that all bits of an and, or, or xor node are statically known, the node is replaced with a literal. * When SplitsEnabled(opt_level) is false (opt_level < 3), if an xor has a single non-constant operand and its accumulated constant mask is all ones, it is simplified to not(x).

  2. Bitwise Mask Decomposition (when SplitsEnabled(opt_level) is true, at opt_level >= 3): * Mask Accumulation: Across all operands of an and, or, or xor node, the pass accumulates a composite mask of known bits: * For and and or, known bits from both fully known and partially known operands are intersected (and) or unioned (or) into the composite mask (with unknown bits set to the identity value: 1 for and, 0 for or). * For xor, fully known constant operands are XORed into the composite mask. * Contiguous Run Splitting: If the composite mask is not the identity (all ones for and, all zeros for or/xor), the bit width is partitioned into maximal contiguous runs [pos, end) where the mask bit is uniform: * Absorbing Runs (0 in and, 1 in or): Replaced with a constant 0 or all_ones literal of width end - pos. * Identity or Inverting Runs (1 in and, 0 in or, or any run in xor): Each non-constant operand whose bits in [pos, end) are not already known to be the identity is sliced to bit_slice(op, pos, end - pos). If multiple sliced operands remain, they are combined with a narrower and/or/xor; for xor runs where the mask bit is 1, the slice (or narrower xor) is inverted with not. * Reassembly: The resulting per-run nodes are joined from MSB to LSB using concat, exposing narrower slices and constants to downstream passes such as BitSliceSimplificationPass.

Example:

// Original IR
mask: bits[8] = literal(value=0xf0)
ret res: bits[8] = and(x, mask)

// Optimized IR (when SplitsEnabled is true)
hi: bits[4] = bit_slice(x, start=4, width=4)
lo_zero: bits[4] = literal(value=0)
ret res: bits[8] = concat(hi, lo_zero)

Header

bool_simp - boolean simplification

Attempts to simplify bitwise / boolean expressions (e.g. of multiple variables).

Note

What follows was generated by the Gemini LLM. Not human verified.

The BooleanSimplificationPass simplifies clusters of bit-parallel Boolean operations (and, or, nand, nor, and not) over arbitrary bit-width bits[N] values by evaluating their local truth tables over up to 3 input frontier nodes and replacing them with a single canonical logical operation or constant literal.

How it Works:

  1. Frontier Tracking (BooleanFlowTracker): A DFS visitor traverses and, or, nand, nor, and not nodes, computing for each node the set of "frontier" inputs (operands not produced by one of those five logical operations). If a node depends on 2 or 3 unique frontier nodes (X, Y, and optionally Z, up to kMaxFrontierNodes = 3), it is eligible for truth-table simplification. Subgraphs that depend on more than 3 frontier nodes are marked with TooManySentinel and skipped.

  2. 8-Bit Truth Table Evaluation (FlowFromFrontierToNode): The frontier nodes are assigned 8-bit initial truth-table vectors representing all 8 input combinations of (X, Y, Z):

    X (frontier[0]): 0b00001111
    Y (frontier[1]): 0b00110011
    Z (frontier[2]): 0b01010101
    

    The pass recursively evaluates the intermediate bitwise operations (and, or, nand, nor, not) with memoization to compute the resulting 8-bit truth table at the target node (for example, and(X, Y) produces 0b00000011).

  3. Canonical Lookup and Replacement (ResolveTruthTable): * Tautology / Contradiction: If the resulting 8-bit truth table is 0b11111111 or 0b00000000, the node is replaced with an all-ones (-1) or all-zeros (0) literal of the node's bit width. * Precomputed Single-Gate Table (GetTruthTables): Otherwise, the 8-bit vector is looked up in a memoized table of canonical forms populated in increasing cost order: 1. A single frontier operand or its negation (x or not(x)). 2. A single N-ary operation (nand, nor, xor, and, or) over 2 or 3 unnegated frontier operands. 3. A single N-ary operation (nand, nor, xor, and, or) over 2 or 3 frontier operands where one or more inputs are negated with not. * If a match is found and the node is not already in that minimal form (MatchesSymmetrical), the node is replaced with the canonical expression.

Example:

// Original IR
fn f(x: bits[42], y: bits[42]) -> bits[42] {
  and_op: bits[42] = and(x, y)
  ret not_op: bits[42] = not(and_op)
}

// Optimized IR (after dead code elimination)
fn f(x: bits[42], y: bits[42]) -> bits[42] {
  ret nand_op: bits[42] = nand(x, y)
}

Header

canon - Canonicalization

IR Canonicalization.

Note

What follows was generated by the Gemini LLM. Not human verified.

The CanonicalizationPass transforms the IR into a standardized, canonical form by iteratively applying local rewrite rules to a fixed point (TransformNodesToFixedPoint) using a StatelessQueryEngine. Establishing consistent structural patterns for common expressions reduces the number of syntactic variations that downstream optimization passes need to match.

Key canonicalizations include:

  1. Moving Constants to the Right in Commutative and Comparison Ops: For binary commutative operations (such as add, umul, and, or, xor, eq, ne) and ordered comparison operations, if operand 0 is a known constant and operand 1 is not, the operands are swapped so the constant is on the right-hand side. Comparison opcodes are reversed accordingly (e.g., ult(C, x) becomes ugt(x, C)).

    one: bits[2] = literal(value=1)
    ret addval: bits[2] = add(one, x)
    

    becomes:

    one: bits[2] = literal(value=1)
    ret addval: bits[2] = add(x, one)
    
  2. Strict Unsigned Comparisons Against Constants: Non-strict unsigned comparisons with a constant on the right-hand side are converted to strict comparisons by adjusting the constant: * uge(x, K) (where K > 0) becomes ugt(x, K - 1). * ule(x, K) (where K < MAX) becomes ult(x, K + 1).

  3. Canonicalizing Unsigned Clamp (Min/Max) Expressions: Two-way select operations driven by an unsigned comparison (ugt or ult) that clamp a value x to a constant bound K are rewritten into a standard form: * Clamp high: x > K - 1 ? K : x, x < K ? x : K, and x < K + 1 ? x : K all canonicalize to sel(ugt(x, K), cases=[x, K]). * Clamp low: x < K + 1 ? K : x, x > K ? x : K, and x > K - 1 ? x : K all canonicalize to sel(ult(x, K), cases=[x, K]).

  4. Converting Subtraction of a Constant to Addition: sub(x, K) where K is a known constant is replaced with add(x, -K) using the two's complement negation of K.

    one: bits[2] = literal(value=1)
    ret subval: bits[2] = sub(x, one)
    

    becomes:

    three: bits[2] = literal(value=3)
    ret addval: bits[2] = add(x, three)
    
  5. Removing No-Op Bit Extensions: Any zero_ext or sign_ext operation whose target bit width equals its operand's bit width is replaced directly by its operand.

  6. Replacing Zero-Extend with Concat: A widening zero_ext operation is replaced with a concat that prepends a zero literal of the extension width to the operand.

    ret ext: bits[42] = zero_ext(x, new_bit_count=42)  // x: bits[33]
    

    becomes:

    zero: bits[9] = literal(value=0)
    ret ext: bits[42] = concat(zero, x)
    
  7. Removing Single-Bit Bitwise Reductions: Bitwise reduction operations (and_reduce, or_reduce, xor_reduce) applied to a 1-bit operand are replaced with the operand itself.

  8. Eliminating Negated Selectors in Binary Selects: If a 2-case binary select (with no default) has not(p) as its selector, the not is bypassed and the two cases are swapped.

    not_p: bits[1] = not(p)
    ret result: bits[8] = sel(not_p, cases=[x, y])
    

    becomes:

    ret result: bits[8] = sel(p, cases=[y, x])
    
  9. Promoting Single-Value Defaults in Selects: If a select (with selector width < 63) has a default value that only covers a single remaining selector value (cases.size() + 1 == 2^width), the default value is appended to cases and removed.

  10. Simplifying Constant Predicates on next_value and state_read: * If a next_value or state_read has a known 1 predicate, the predicate is removed to make the operation unconditional. * If a next_value has a known 0 predicate, it is replaced with an empty tuple literal () and removed. When decouple_state_access is enabled, a state_read with a known 0 predicate is similarly replaced with a zero literal and removed (in coupled mode it is preserved for downstream state legalization).

Header

canonicalize_proc_state - canonicalize proc state representation

Bring proc-state representation to the canonical 'flat' representationother passes expect.

Text-proto

Options Set

Run to a fixedpoint.

Invoked Passes

channel_legalization - Legalize multiple send/recvs per channel

Pass that legalizes multiple send/receive operations per channel.

This pass adds cross-activation tokens to guarantee that later activations of a proc cannot send or receive on a channel until all previous activations have completed working with that channel.

Note

What follows was generated by the Gemini LLM. Not human verified.

The ChannelLegalizationPass legalizes streaming channels (kStreaming) that are accessed by multiple send or multiple receive operations within a Proc. All multiple sends (or multiple receives) on a channel must reside in the same Proc, map uniquely to that channel, and (for receives) be blocking.

For each streaming channel with multiple sends or receives, the pass performs two steps:

  1. Strictness Verification and Mutual Exclusion (CheckMutualExclusion): The pass builds a projected token dependency DAG (GetProjectedDAG) over the channel's operations and enforces the channel's ChannelStrictness: * kTotalOrder: Verifies (CheckProjectedDAG) that the existing token DAG already forms a strict linear chain where the first operation depends only on token param(s) and each subsequent operation depends on the previous one. * kRuntimeOrdered: Respects existing token dependencies; for any pair of operations not ordered by a token dependency chain, inserts a runtime assert checking that their predicates are not simultaneously true (or fails at compile time if both are unconditional). * kProvenMutuallyExclusive: Ignores token dependencies and uses a Z3 SMT solver (solvers::SolverKind::kZ3) with proc state assumptions (GetProcStateAssumptions) to formally prove at compile time that at most one operation on the channel can be active per activation. * kRuntimeMutuallyExclusive: Ignores token dependencies and inserts a runtime assert checking that no other operation on the channel is active in the same activation. * kArbitraryStaticOrder: Imposes a total topological order in the projected DAG so all operations are treated as ordered.

  2. Cross-Activation Token Insertion: To ensure that an activation cannot issue a send or receive on the channel before all operations on that channel from previous activations have completed: * For each operation in the group, a token-typed state element (implicit_token__<op_name>) is appended to the Proc. * A next_value node updates that state element with the operation's output token (tuple_index(recv, index=0) for receive, or send itself for send), gated by the operation's predicate. * Each operation's input token is replaced with an after_all combining its original input token with the state_reads of all newly added implicit token state elements for that channel.

Example:

chan in(bits[32], id=0, kind=streaming, ops=receive_only,
        flow_control=ready_valid, strictness=proven_mutually_exclusive)

top proc my_proc() {
  tok: token = literal(value=token)
  recv0: (token, bits[32]) = receive(tok, predicate=p0, channel=in)
  recv1: (token, bits[32]) = receive(tok, predicate=p1, channel=in)
}

After ChannelLegalizationPass (assuming Z3 proves !(p0 && p1)):

top proc my_proc(implicit_token__recv0: token,
                 implicit_token__recv1: token, init={token, token}) {
  tok: token = literal(value=token)
  prev_tok0: token = state_read(state_element=implicit_token__recv0)
  prev_tok1: token = state_read(state_element=implicit_token__recv1)
  tok_all0: token = after_all(tok, prev_tok0, prev_tok1)
  recv0: (token, bits[32]) = receive(tok_all0, predicate=p0, channel=in)
  recv0_tok: token = tuple_index(recv0, index=0)
  next_tok0: () = next_value(state_element=implicit_token__recv0,
                             value=recv0_tok, predicate=p0)

  tok_all1: token = after_all(tok, prev_tok0, prev_tok1)
  recv1: (token, bits[32]) = receive(tok_all1, predicate=p1, channel=in)
  recv1_tok: token = tuple_index(recv1, index=0)
  next_tok1: () = next_value(state_element=implicit_token__recv1,
                             value=recv1_tok, predicate=p1)
}

Header

collapse_select_chains - BDD-based Select Chain Collapsing

Pass which collapses chains of selects with disjoint selectors into a single one-hot-select.

Chains of binary select operations, particularly where one case of a select feeds into another select (e.g., sel(pred_a, {val_a, sel(pred_b, {val_b, default_val})})), are transformed into a single one_hot_select if the selectors are provably disjoint (at most one can be true at any given time). This simplifies the IR structure and can lead to more efficient hardware implementations.

Note

What follows was generated by the Gemini LLM. Not human verified.

The CollapseSelectChainsPass identifies chains of select operations whose selector bits are mutually exclusive and collapses them into a single one_hot_sel operation, reducing logic depth and mux delay.

How it Works:

  1. Query Engine Setup: The pass uses a UnionQueryEngine combining a StatelessQueryEngine and a BddQueryEngine to reason about Boolean relationships (such as mutual exclusivity and exhaustiveness) among selector bits.

  2. Chain Discovery (GetSelectNodeChains): The pass traverses the function in reverse topological order (ReverseTopoSort) to build chains of bits-typed select operations (IsChainableSelect, sorted by root node ID in ascending order) where the fall-through branch of one select feeds into a single-use inner select: * Binary sel: Either a 2-case sel without a default (where case[1] is the selected value when selector == 1 and case[0] is the fall-through) or a 1-case sel with a 1-bit selector and a default (where default is selected when selector == 1 and case[0] is the fall-through). * priority_sel: Contributes all of its cases (selected by bits 0..N-1 of its selector) and chains through its default_value. * one_hot_sel: Contributes all of its cases and terminates the chain (with no final_default).

  3. Subchain Selection and Profitability (DetermineBestSelectSubchain): * Searches from the root of each chain toward the leaf across contiguous subchains whose selector bit locations (TreeBitLocation) satisfy query_engine.AtMostOneTrue(...), selecting the mutually exclusive subchain with the most total cases (breaking ties in favor of subchains closer to the root). * Length Threshold: To avoid interfering with other select optimizations on small mux trees, a subchain is only collapsed if it contains more than 4 total active cases (total_cases > 4, i.e., at least 5 cases) and has at least 2 select nodes (subchain_length > 1). * Default Computation and Elimination: If the selected subchain ends before the leaf of the full chain, the next select node in the chain becomes the subchain's final_default. If the subchain has a final_default and query_engine.AtLeastOneTrue(...) proves that at least one selector bit in the subchain is always active, the unreachable final_default is dropped.

  4. Collapsing to one_hot_sel (CollapseSelectNodeChain): * If final_default may still be reached (all selector bits can be simultaneously zero), a default selector bit is constructed as the conjunction (and) of eq(selector, 0) across all selects in the subchain, and final_default is placed as case[0] (the LSB case). * Active cases are ordered from the leaf of the subchain to the root. * The new selector is formed by concatenating the subchain selectors from root (MSB) to leaf, followed by the default selector bit (LSB) if present, and the root select is replaced with one_hot_sel.

Example (5 mutually exclusive predicates p0..p4 where at most one is 1):

s0: bits[8] = sel(p0, cases=[d, v0])
s1: bits[8] = sel(p1, cases=[s0, v1])
s2: bits[8] = sel(p2, cases=[s1, v2])
s3: bits[8] = sel(p3, cases=[s2, v3])
ret s4: bits[8] = sel(p4, cases=[s3, v4])

becomes:

z0: bits[1] = eq(p0, literal(0))
z1: bits[1] = eq(p1, literal(0))
z2: bits[1] = eq(p2, literal(0))
z3: bits[1] = eq(p3, literal(0))
z4: bits[1] = eq(p4, literal(0))
all_zero: bits[1] = and(z4, z3, z2, z1, z0)
sel_bits: bits[6] = concat(p4, p3, p2, p1, p0, all_zero)
ret s4: bits[8] = one_hot_sel(sel_bits, cases=[d, v0, v1, v2, v3, v4])

Header

comparison_simp - Comparison Simplification

Simplifies logical operations on the results of comparison operations. For example:

eq(x, 0) && ne(x, 1) => eq(x, 0) eq(x, 0) && ne(x, 0) => 0 eq(x, 0) || ne(x, 0) => 1

Note

What follows was generated by the Gemini LLM. Not human verified.

The ComparisonSimplificationPass simplifies comparisons and Boolean logic trees over comparisons across three stages in a topological traversal:

  1. Range-Equivalence Simplification (ComputeRangeEquivalence): * Using a StatelessQueryEngine, the pass maps 1-bit nodes to a RangeEquivalence{node, IntervalSet}, indicating that the 1-bit node evaluates to 1 if and only if node lies within IntervalSet. * Base intervals are seeded from comparisons against known constants (eq, ne, ult, ugt) and propagated through and, or, not, nand, and nor operations whose operands all constrain the same underlying node (using interval intersection, union, and complement). * Each node with a computed RangeEquivalence{x, range} is simplified based on its normalized IntervalSet (skipping nodes that are already in minimal comparison form or that are single not inversions of multi-use comparisons): * Maximal range: Replaced with literal(1). * Empty range: Replaced with literal(0). * Single value [C, C]: Replaced with eq(x, C). * Complement of a single value C: Replaced with ne(x, C). * Contiguous prefix [0, C - 1]: Replaced with ult(x, C). * Contiguous suffix [C + 1, MAX]: Replaced with ugt(x, C).

  2. Removing Non-Wrapping Unit Offsets (SimplifyComparisonWithUnitOffset): * Rewrites ordered signed and unsigned comparisons (ult, ule, ugt, uge, slt, sle, sgt, sge) where one operand adds or subtracts 1 (+ 1 or - 1), toggling strictness to eliminate the offset when PartialInfoQueryEngine proves the base operand cannot take on the wrapping boundary value (MAX for + 1, MIN for - 1): * a < b + 1 => a <= b * a >= b + 1 => a > b * a <= b - 1 => a < b * a > b - 1 => a >= b

  3. Deduplicating Derived Comparisons (TransformDerivedComparisons): * Scans comparisons in topological order and reuses an earlier comparison (a cmp b) when a later comparison is: * Commuted (e.g., ult(b, a) becomes ugt(a, b)). * Inverted (e.g., ule(a, b) becomes not(ugt(a, b))). * Commuted and inverted (e.g., uge(b, a) becomes not(ugt(a, b))).

Example (eq(x, 0) && ne(x, 1)):

fn f(x: bits[32]) -> bits[1] {
  literal.0: bits[32] = literal(value=0)
  literal.1: bits[32] = literal(value=1)
  x_eq_0: bits[1] = eq(x, literal.0)
  x_ne_1: bits[1] = ne(x, literal.1)
  ret and.final: bits[1] = and(x_eq_0, x_ne_1)
}

ComputeRangeEquivalence maps x_eq_0 to [[0, 0]] and x_ne_1 to [[0, 0], [2, MAX]]. Their intersection at and.final is [[0, 0]], so and.final is replaced with a single equality comparison (shown after dead code elimination):

fn f(x: bits[32]) -> bits[1] {
  literal.0: bits[32] = literal(value=0)
  ret eq.final: bits[1] = eq(x, literal.0)
}

Header

concat_select_removal - Concat Select Removal

Replaces a concat of selects with the same selectors with a single select of concats. This seems to be optimized better by synthesis tools.

For example, (concat (select a b c) (select a d e)) would be replaced with (select a (concat b d) (concat c e))

Or (concat X (select a b c) (select a d e) Y) would be replaced with (Concat X (select a (concat b d) (concat c e)) Y)

We will not add additional bit-slices to support things like (concat (select a b c) X (select a d e)) TODO(allight): Should we do this?

Nor will we combine selects with unlike selectors. (concat (select a b c) (select d e f))

Note

What follows was generated by the Gemini LLM. Not human verified.

The ConcatSelectRemovalPass hoists select operations (sel, priority_sel, and one_hot_sel, represented uniformly via GenericSelect) above concat operations when adjacent operands of a concat share the same select kind and selector. Combining narrow parallel selects with identical control into a single wider select over concatenated data branches reduces control fanout and improves synthesis quality.

How it Works:

  1. Identifying Mergeable Runs (FindConcatSelects, CanMerge, PickTransform): * The pass traverses nodes in topological order and inspects each concat operation using a StatelessQueryEngine. * Adjacent concat operands that are select operations can be merged (CanMerge) if: * They have the same GenericSelect kind (sel, priority_sel, or one_hot_sel). * Their selectors are provably equal via NodesKnownUnsignedEquals(a.selector(), b.selector()). * In scheduled functions (IsScheduled()), both select nodes are staged (IsStaged()) and belong to the same pipeline stage (GetStageIndex). * Contiguous runs of 2 or more compatible selects within a concat's operands are grouped for merging, while non-select operands (or single unmerged selects) are preserved in place.

  2. Rewriting to Select of Concats (TransformToSelectOfConcats, DoTransform): * For each mergeable run of selects, the pass determines the maximum number of explicit cases (and whether a default value is needed) from the select in the run with the most explicit cases. * For each case index i (and for the default branch, if present), it collects the i-th case from every select in the run (using a select's default_value when i >= select.cases().size()) and concatenates them into a new concat node. * It creates a single merged select (CloneSelectLike) choosing among the per-case concat nodes. If the function is scheduled, all new concat nodes and the merged select are added to the original stage (AddNodeToStage). * If all operands of the original concat were merged into a single select, the concat is replaced directly by that select; otherwise, it is replaced by an outer concat combining the unmerged operands and the newly merged select(s).

Example:

fn f(s: bits[1], a: bits[4], b: bits[4],
     c: bits[8], d: bits[8]) -> bits[12] {
  sel_hi: bits[4] = sel(s, cases=[a, b])
  sel_lo: bits[8] = sel(s, cases=[c, d])
  ret result: bits[12] = concat(sel_hi, sel_lo)
}

becomes:

fn f(s: bits[1], a: bits[4], b: bits[4],
     c: bits[8], d: bits[8]) -> bits[12] {
  case_0: bits[12] = concat(a, c)
  case_1: bits[12] = concat(b, d)
  ret result: bits[12] = sel(s, cases=[case_0, case_1])
}

Header

concat_simp - Concat simplification

Pass which simplifies concats. This includes removing single-operand concats, flattening trees of dependent concats, and others.

Note

What follows was generated by the Gemini LLM. Not human verified.

The ConcatSimplificationPass simplifies concat operations and optimizes operations that consume or feed into concats. It first processes concat nodes iteratively using a worklist (so newly created or modified concats are re-evaluated), and then performs a topological pass over the graph when narrowing optimizations are enabled (options.narrowing_enabled()).

Key optimizations include:

  1. Removing Single-Operand Concats: A concat with a single operand is replaced directly by that operand:

    concat(x) => x
    
  2. Flattening Trees of Concats (FlattenConcatTree): Nested concat operations are flattened into a single concat:

    concat(a, b, concat(c, concat(d, e))) => concat(a, b, c, d, e)
    
  3. Merging Consecutive Constant Operands (ReplaceConsecutiveConstantOperands): Using a StatelessQueryEngine, consecutive operands with known constant values are merged into a single wider literal operand.

  4. Eliminating Zero-Bit Operands: Any bits[0] operands are removed from the concat operand list.

  5. Hoisting reverse Above concat (when NarrowingEnabled): If NarrowingEnabled(opt_level) is true and a concat has a single reverse user (and no other users besides bitwise reductions), the reverse is distributed to each operand in reverse order:

    reverse(concat(a, b, c)) => concat(reverse(c), reverse(b), reverse(a))
    
  6. Merging Consecutive Forward Bit Slices (ReplaceConsecutiveBitSlices): Consecutive bit_slice operands slicing contiguous ranges from the same source node in descending bit order (slice.start + slice.width == prev.start) are merged into a single wider bit_slice (or replaced by the source node itself if the merged slice covers the full bit width):

    concat(bit_slice(x, start=4, width=4), bit_slice(x, start=0, width=4))
    // => x  (when x is bits[8])
    
  7. Merging Consecutive Reversed Bit Slices (ReplaceConsecutiveReversedSlices): Consecutive operands that are either reverse(bit_slice(x, ...)) or 1-bit bit_slice(x, start, 1) (which are trivially self-reversed) from the same source node in ascending bit order (prev.start + prev.width == slice.start) are merged into a single reverse(bit_slice(x, ...)) (or reverse(x) if covering the full source width):

    concat(reverse(bit_slice(x, start=0, width=4)),
           reverse(bit_slice(x, start=4, width=4)))
    // => reverse(x)  (when x is bits[8])
    
  8. Narrowing and Hoisting Binary Bitwise Users of Padded Concats (TryNarrowAndHoistBitWiseOperation, when narrowing_enabled()): When a 2-operand concat has one variable operand and one constant operand that is all-zeros (0) or all-ones (~0) of at least 6 bits (kMinNarrowingBits = 6), binary bitwise users (and, or, xor) are narrowed to operate only on the variable bits: * Masking constant (and with 0, or or with ~0): The constant bits pass through unchanged to the new concat. * Identity constant (xor with 0, or with 0, or and with ~0): The corresponding bits of the other operand are sliced and concatenated alongside the narrowed bitwise operation.

    // Given x: bits[10], b: bits[4]
    or(x, concat(0b111111, b))
    // => concat(0b111111, or(bit_slice(x, start=0, width=4), b))
    
  9. Hoisting Bitwise Operations Above Concats (TryHoistBitWiseOperation and TryHoistBitWiseWithConstant, when narrowing_enabled()): * If a binary bitwise operation has one known-constant operand and one concat operand, the operation is distributed across each concat operand using slices of the constant. * If all operands of a bitwise operation are concats, the pass finds the union of bit-range boundaries across the input concats (GetBitRangeUnionOfInputConcats), slices each input concat to those aligned sub-ranges, applies the bitwise operation to each sub-range, and concatenates the results:

    xor(concat(a, b), concat(c, d)) => concat(xor(a, c), xor(b, d))
    
  10. Distributing eq and ne Across Concats (TryDistributeReducibleOperation, when narrowing_enabled()): Distributes equality (eq) and inequality (ne) comparisons with a concat across the concat's operands by slicing the other comparison operand to match each piece and combining the element-wise comparisons with and (for eq) or or (for ne):

    // Given x: bits[5], y: bits[10], z: bits[15]
    eq(concat(x, y), z)
    // => and(eq(x, bit_slice(z, start=10, width=5)),
    //        eq(y, bit_slice(z, start=0, width=10)))
    
  11. Bypassing Bitwise Reductions of Concats (TryBypassReductionOfConcatenation, when narrowing_enabled()): Replaces and_reduce, or_reduce, or xor_reduce of a concat with an and, or, or xor of the reductions of each non-zero-width operand (using 1-bit operands directly without a reduction node):

    or_reduce(concat(a, b)) => or(or_reduce(a), or_reduce(b))
    

Header

cond_spec(Bdd) - Conditional specialization

Pass which specializes arms of select operations based on their selector value. When analyzing a particular arm of a sel, the value of the selector is known. This knowledge can be used to simplify the expression within the arm.

Note

What follows was generated by the Gemini LLM. Not human verified.

For example, consider the following IR:

fn f(a: bits[1], b: bits[31], z: bits[32]) -> bits[32] {
  concat: bits[32] = concat(a, b)
  ret sel.2: bits[32] = sel(a, cases=[z, concat])
}

In the sel operation, the selector is a. When considering case[1] (the concat operation), we know that a must have the value 1. Therefore, the concat(a, b) can be simplified to concat(1, b). The pass will transform the sel to:

sel.2: bits[32] = sel(a, cases=[z, concat(literal(1), b)])

This optimization applies to sel, priority_sel, and one_hot_sel. It can also use Binary Decision Diagrams (BDDs) for more powerful analysis of the conditions.

Header

cond_spec(false) - Conditional specialization

Pass which specializes arms of select operations based on their selector value. When analyzing a particular arm of a sel, the value of the selector is known. This knowledge can be used to simplify the expression within the arm.

Note

What follows was generated by the Gemini LLM. Not human verified.

For example, consider the following IR:

fn f(a: bits[1], b: bits[31], z: bits[32]) -> bits[32] {
  concat: bits[32] = concat(a, b)
  ret sel.2: bits[32] = sel(a, cases=[z, concat])
}

In the sel operation, the selector is a. When considering case[1] (the concat operation), we know that a must have the value 1. Therefore, the concat(a, b) can be simplified to concat(1, b). The pass will transform the sel to:

sel.2: bits[32] = sel(a, cases=[z, concat(literal(1), b)])

This optimization applies to sel, priority_sel, and one_hot_sel. It can also use Binary Decision Diagrams (BDDs) for more powerful analysis of the conditions.

Header

cond_spec(noBdd) - Conditional specialization

Pass which specializes arms of select operations based on their selector value. When analyzing a particular arm of a sel, the value of the selector is known. This knowledge can be used to simplify the expression within the arm.

Note

What follows was generated by the Gemini LLM. Not human verified.

For example, consider the following IR:

fn f(a: bits[1], b: bits[31], z: bits[32]) -> bits[32] {
  concat: bits[32] = concat(a, b)
  ret sel.2: bits[32] = sel(a, cases=[z, concat])
}

In the sel operation, the selector is a. When considering case[1] (the concat operation), we know that a must have the value 1. Therefore, the concat(a, b) can be simplified to concat(1, b). The pass will transform the sel to:

sel.2: bits[32] = sel(a, cases=[z, concat(literal(1), b)])

This optimization applies to sel, priority_sel, and one_hot_sel. It can also use Binary Decision Diagrams (BDDs) for more powerful analysis of the conditions.

Header

cond_spec(true) - Conditional specialization

Pass which specializes arms of select operations based on their selector value. When analyzing a particular arm of a sel, the value of the selector is known. This knowledge can be used to simplify the expression within the arm.

Note

What follows was generated by the Gemini LLM. Not human verified.

For example, consider the following IR:

fn f(a: bits[1], b: bits[31], z: bits[32]) -> bits[32] {
  concat: bits[32] = concat(a, b)
  ret sel.2: bits[32] = sel(a, cases=[z, concat])
}

In the sel operation, the selector is a. When considering case[1] (the concat operation), we know that a must have the value 1. Therefore, the concat(a, b) can be simplified to concat(1, b). The pass will transform the sel to:

sel.2: bits[32] = sel(a, cases=[z, concat(literal(1), b)])

This optimization applies to sel, priority_sel, and one_hot_sel. It can also use Binary Decision Diagrams (BDDs) for more powerful analysis of the conditions.

Header

const_fold - Constant folding

Pass which performs constant folding. Every op with only literal operands is replaced by an equivalent literal.

Note

What follows was generated by the Gemini LLM. Not human verified.

The ConstantFoldingPass evaluates operations whose operands are all known compile-time constants and replaces their uses with a new literal node containing the computed result.

How it Works:

The pass traverses the nodes of a FunctionBase in topological order (context.TopoSort(f)) using a StatelessQueryEngine. Because nodes are visited in topological order, replacing an operation with a literal immediately exposes that constant to downstream users during the same pass, folding entire constant subgraphs in a single traversal.

A node is eligible for constant folding (NodeIsConstantFoldable) if all of the following hold:

  1. Has Users or Implicit Use: The node has at least one user or is implicitly used by the FunctionBase (such as a function return value).
  2. Not Already a Literal: The node is not already a literal.
  3. No Token Types: The node's type does not contain a token (!TypeHasToken(node->GetType())).
  4. Not Side-Effecting (Except gate): Side-effecting operations cannot be folded, with the exception of gate, which can be folded when its condition and data operands are constant.
  5. All Operands Are Known Constants: Every operand is fully known according to StatelessQueryEngine::IsFullyKnown.

For each eligible node, the pass extracts the constant Value of each operand, evaluates the node via InterpretNode, and replaces its uses with a newly created literal node (ReplaceUsesWithNew<Literal>). The pass does not delete the replaced nodes itself; they are cleaned up by subsequent DeadCodeEliminationPass runs.

Example:

fn IdenticalLiterals() -> bits[8] {
  literal.1: bits[8] = literal(value=42)
  literal.2: bits[8] = literal(value=123)
  ret add.3: bits[8] = add(literal.1, literal.2)
}

After ConstantFoldingPass (and subsequent dead code elimination):

fn IdenticalLiterals() -> bits[8] {
  ret literal.4: bits[8] = literal(value=165)
}

Header

cse - Common subexpression elimination

Pass which performs common subexpression elimination. Equivalent ops with the same operands are commoned. The pass can find arbitrarily large common expressions.

Note

What follows was generated by the Gemini LLM. Not human verified.

The CsePass (Common Subexpression Elimination) identifies and merges equivalent computations within a FunctionBase. Because it traverses the IR in topological order and canonicalizes operands to unique arena pointers, it can detect and merge arbitrarily deep isomorphic expression trees in a single pass.

How it Works:

  1. Canonical Node Representation (CseNode and CseNodeArena): As the pass visits each live node (!node->IsDead()) in topological order, CseNodeArena interns a canonical CseNode key consisting of: * Opcode (Op) and Result Type (Type*). * Canonical Operands (std::vector<CseNode*>): Pointers to the already-interned CseNodes of the node's operands. For commutative operations (OpIsCommutative), operand pointers are sorted by their arena ID so commuted expressions map to the same CseNode. * Pipeline Stage: If the node is staged in a scheduled function (IsStaged), its stage index (GetStageIndex) is included so nodes are only merged within the same pipeline stage. * Operation Metadata: Captures attributes not reflected in the opcode, operands, or result type: * array_index, array_update: assumed_in_bounds. * bit_slice: start offset. * one_hot: LsbOrMsb priority. * tuple_index: element index. * counted_for: trip_count, stride, and body function. * invoke, map: target function pointer. * literal: serialized ValueProto when common_literals is true, or a unique ID when common_literals is false. * Non-CSE-able operations (param, state_read, next_value, receive, send, assert, cover, trace, register and port ops, etc., including all side-effecting ops except gate): assigned a unique ID so they never compare equal to any other node.

  2. Grouping and Representative Replacement (RunCse): * Live nodes that intern to the same CseNode* are collected into an equivalence bucket. * For each bucket with multiple nodes, a single representative is chosen deterministically (CompareName): preferring nodes with an assigned name (HasAssignedName()), then shorter assigned names, and finally the lowest node id(). * All other nodes in the bucket have their uses replaced by the representative (ReplaceUsesWith), leaving the duplicate nodes dead for subsequent DeadCodeEliminationPass cleanup.

Example:

fn nontrivial(x: bits[8], y: bits[8], z: bits[8]) -> bits[8] {
  and.1: bits[8] = and(x, y)
  neg.2: bits[8] = neg(and.1)
  or.3: bits[8] = or(neg.2, z)

  and.4: bits[8] = and(y, x)      // Commutatively equivalent to and.1
  neg.5: bits[8] = neg(and.4)     // Equivalent to neg.2
  or.6: bits[8] = or(neg.5, z)    // Equivalent to or.3

  ret add.7: bits[8] = add(or.3, or.6)
}

After CsePass (and subsequent dead code elimination):

fn nontrivial(x: bits[8], y: bits[8], z: bits[8]) -> bits[8] {
  and.1: bits[8] = and(x, y)
  neg.2: bits[8] = neg(and.1)
  or.3: bits[8] = or(neg.2, z)
  ret add.7: bits[8] = add(or.3, or.3)
}

Header

dataflow - Dataflow Optimization

An optimization which uses a lattice-based dataflow analysis to find equivalent nodes in the graph and replace them with a simpler form. The analysis traces through tuples, arrays, and select operations. Optimizations which can be performed by this pass:

tuple_index(tuple(x, y), index=1) => y

select(selector, {z, z}) => z

array_index(array_update(A, x, index={42}), index={42}) => x

Note

What follows was generated by the Gemini LLM. Not human verified.

The DataflowSimplificationPass uses a lattice-based dataflow analysis (NodeSourceDataflowVisitor, built on DataflowVisitor<NodeSource>) to track the origin of every leaf element (tuple fields, array elements, and leaf bits or token values) through structural and control-flow operations (tuple, tuple_index, array, array_index, array_slice, array_update, array_concat, identity, sel, priority_sel, and one_hot_sel). Nodes whose leaf elements originate from the exact same sources are replaced with earlier equivalent nodes or reconstructed directly from existing element nodes.

How it Works:

  1. Leaf-Level Source Analysis (NodeSourceDataflowVisitor): * The pass traverses the function in topological order and computes a LeafTypeTree<NodeSource> for every node. * Each leaf holds a NodeSource(node, tree_index) identifying the earliest node and aggregate index path from which that leaf value statically originates. * When joining branches in select or dynamic array operations (JoinElements), if all possible data sources for a leaf element are identical, that common NodeSource is preserved; otherwise, the join falls back to the current node (NodeSource(node, index)).

  2. Replacing Equivalent Nodes via source_map: * During a topological walk, the pass inserts each node's LeafTypeTreeView<NodeSource> into source_map. * If a later node has the exact same LeafTypeTreeView<NodeSource> as an earlier node in source_map (and is not an empty type with zero flat bits and no tokens, which is skipped via IsEmptyType to avoid infinite replacement loops between empty-typed nodes), the later node is replaced directly with the earlier node (ReplaceUsesWith). * This single mechanism handles unboxing (tuple_index(tuple(x, y), 1) -> y), redundant select elimination (sel(s, cases=[z, z]) -> z), forwarding through array updates, and replacing an array reconstructed from ordered array_index operations of an existing array a back with a:

      ```
      // Original:
      e0: bits[32] = array_index(a, indices=[zero])
      e1: bits[32] = array_index(a, indices=[one])
      ret arr: bits[32][2] = array(e0, e1)
    
      // After optimization (arr has the same NodeSource tree as 'a'):
      ret a: bits[32][2] = param(name=a)
      ```
    
  3. Materializing Arrays from Existing Element Nodes (MaybeReplaceWithArrayOfExistingNodes): * If an array-typed node is not already in source_map (and is not a literal, array, array_index, or empty type—avoiding array and array_index prevents infinite loops with ArraySimplificationPass), the pass checks whether the NodeSource view for every element 0..size-1 of the array is already present as a standalone node in source_map. * If all element sources exist in source_map, the operation (such as a chain of array_updates, an array_concat, or an array_slice) is replaced with a direct array(e_0, e_1, ..., e_{n-1}) node.

Header

dce - Dead Code Elimination

class DeadCodeEliminationPass removes dead nodes from a FunctionBase by starting from unused deletable nodes and iteratively removing them and any operands that become unused.

Note

What follows was generated by the Gemini LLM. Not human verified.

The DeadCodeEliminationPass (DCE) is a fundamental optimization pass in XLS that removes "dead" or unused nodes from a FunctionBase (a function, proc, or block). Dead code refers to any operation whose result has no consumers and is not required for its observable outputs or side effects. Removing dead code simplifies the IR graph, reduces synthesized hardware area, and speeds up subsequent optimization passes.

How it Works:

Rather than marking live nodes from roots, the pass uses a bottom-up worklist algorithm starting from nodes that already have zero users:

  1. Deletability Criterion (is_deletable): A node n is eligible for deletion if all of the following hold: * No Implicit Uses: !n->function_base()->HasImplicitUse(n) (for example, a function's return value node or a legacy proc's next-state node has an implicit use and cannot be deleted). * Not an invoke: !n->Is<Invoke>(). Invoked functions are conservatively preserved by DCE because they may contain side-effecting operations; InliningPass is responsible for eliminating invoke nodes. * Not Side-Effecting (Except gate): !OpIsSideEffecting(n->op()) || n->Is<Gate>(). Side-effecting nodes such as assert, cover, trace, send, receive, next_value, register_write, instantiation_input, output_port, and param are preserved even when they have no explicit users. gate is specially exempted so unused gated values can be eliminated. (Gate is considered side-effecting so it can force itself into the verilog output.)

  2. Worklist Initialization: The pass scans f->nodes() and seeds a FIFO worklist (std::deque<Node*>) with every node n where n->users().empty() and is_deletable(n) is true.

  3. Iterative Removal: While the worklist is non-empty, the pass pops a node from the front of the queue: * It inspects each unique operand of the node (using ForEachUnique so an operand referenced multiple times by the same node is only checked once). If an operand is only used by this node (HasSingleUse(operand)) and satisfies is_deletable(operand), that operand will become userless once the current node is removed, so it is pushed onto the worklist. * The current node is removed from the FunctionBase via f->RemoveNode(node).

  4. Optimization Context Garbage Collection: If any nodes were removed during the pass, context.CollectGarbage() is called to clean up cached query engine and analysis state associated with the deleted nodes.

Example:

Consider a function with dead intermediate operations:

// Original IR snippet
fn some_dead_code(x: bits[42], y: bits[42]) -> bits[42] {
  neg.1: bits[42] = neg(x)
  add.2: bits[42] = add(x, y)      // Only used by dead node neg.3
  neg.3: bits[42] = neg(add.2)     // Dead: zero users
  ret sub.4: bits[42] = sub(neg.1, y)
}

DeadCodeEliminationPass executes as follows: 1. Initial scan finds neg.3 has zero users and is deletable, so the worklist is initialized to [neg.3]. (sub.4 has zero explicit users but is the function return value, so HasImplicitUse(sub.4) is true.) 2. neg.3 is popped. Its unique operand add.2 has a single use (neg.3) and is deletable, so add.2 is added to the worklist. neg.3 is removed. 3. add.2 is popped. Its operands x and y still have other uses (and are param nodes), so neither is added to the worklist. add.2 is removed.

The resulting IR is:

// Optimized IR (after DCE)
fn some_dead_code(x: bits[42], y: bits[42]) -> bits[42] {
  neg.1: bits[42] = neg(x)
  ret sub.4: bits[42] = sub(neg.1, y)
}

Header

dfe - Dead Function Elimination

Dead Function Elimination.

Note

What follows was generated by the Gemini LLM. Not human verified.

DeadFunctionEliminationPass (DFE) is a package-level optimization pass that removes unreachable functions, procs, and blocks (collectively FunctionBases) as well as unused global channels from a Package.

The pass requires that a top entity be specified on the package (p->GetTop()); if no top is set, the pass returns false without making any changes.

How it Works:

  1. Identifying Live Roots (FunctionBaseLiveness): * If top is a Function or Block, top is the sole live root (and no global channels are marked live). * If top is a new-style Proc (top->is_new_style_proc() with proc-scoped channels), the pass runs ProcElaboration::Elaborate(top) and treats all elaborated procs in the hierarchy (elab.procs()) as live roots. * If top is an old-style Proc (using package-level global channels), the pass seeds a worklist with top and any proc in the package that accesses an external channel (channel->supported_ops() != ChannelOps::kSendReceive, i.e., send_only or receive_only). It then performs a breadth-first traversal across the proc-to-channel graph so that any proc communicating with a live proc over an internal SendReceive channel is also marked as a live root, and every channel used by a live proc is recorded in live_global_channels.

  2. Reachability Traversal (MarkReachedFunctions): Starting from each live root, the pass performs a depth-first search (DFS) to mark all transitively referenced FunctionBases: * counted_for nodes mark their body() function. * invoke and map nodes mark their to_apply() function. * If a visited FunctionBase is a Block, any sub-blocks referenced via BlockInstantiation in GetInstantiations() are recursively marked.

  3. Removal of Dead Entities: * Every FunctionBase in p->GetFunctionBases() not in the reached set is evicted from the OptimizationContext (context.Abandon(f)) and removed from the package (p->RemoveFunctionBase(f)). * Every global channel in p->channels() not in live_global_channels is removed via p->RemoveChannel(channel).

Example:

Consider a package with three functions where f_top is the top entity and invokes f_live, while f_dead is never referenced:

package my_package

fn f_dead() -> bits[32] {
  ret literal.0: bits[32] = literal(value=42)
}

fn f_live(x: bits[32]) -> bits[32] {
  literal.1: bits[32] = literal(value=1)
  ret add.2: bits[32] = add(x, literal.1)
}

top fn f_top(y: bits[32]) -> bits[32] {
  ret invoke.3: bits[32] = invoke(y, to_apply=f_live)
}

After DeadFunctionEliminationPass runs, f_dead is removed because it is not reachable from f_top:

package my_package

fn f_live(x: bits[32]) -> bits[32] {
  literal.1: bits[32] = literal(value=1)
  ret add.2: bits[32] = add(x, literal.1)
}

top fn f_top(y: bits[32]) -> bits[32] {
  ret invoke.3: bits[32] = invoke(y, to_apply=f_live)
}

Header

fixedpoint_proc_state_flattening - Proc State Flattening

Prepare proc state for further analysis by removing arrays and tuples.

Text-proto

Options Set

Run to a fixedpoint.

Invoked Passes

fixedpoint_simp - Fixed-point Simplification

Standard simplification pipeline.

This is run to a fixedpoint and avoids many time-consuming analyses.

Text-proto

Options Set

Run to a fixedpoint.

Invoked Passes

fixedpoint_simp(2) - Max-2 Fixed-point Simplification

Standard simplification pipeline.

Opt level is capped at 2

Text-proto

Options Set

Run to a fixedpoint.

Cap opt level: 2

Invoked Passes

fixedpoint_simp(3) - Max-3 Fixed-point Simplification

Standard simplification pipeline.

Opt level is capped at 3

Text-proto

Options Set

Run to a fixedpoint.

Cap opt level: 3

Invoked Passes

fixedpoint_simp(>=1,<=2) - Min-1 Max-2 Fixedpoint Simplification

Standard simplification pipeline.

Opt level is capped at 2 and skipped if less than 1

Text-proto

Options Set

Run to a fixedpoint.

Min opt level: 1

Cap opt level: 2

Invoked Passes

full-inlining - full function inlining passes

Fully inline all functions in a single step.

Text-proto

Invoked Passes

ident_remove - Identity Removal

Identity Removal - eliminate all identity() expressions.

Note

What follows was generated by the Gemini LLM. Not human verified.

The IdentityRemovalPass is a pass that simplifies the Intermediate Representation (IR) by bypassing all identity operations in a FunctionBase. An identity operation (Op::kIdentity) simply forwards its single operand unchanged.

How it Works:

  1. Single Forward Pass: The pass iterates once through f->nodes().
  2. Use Replacement: For each node with node->op() == Op::kIdentity, it calls node->ReplaceUsesWith(node->operand(0)), rewiring all explicit consumers (as well as implicit uses such as a function's return value) directly to the operand of the identity node.
  3. Cleanup by DCE: IdentityRemovalPass does not delete the now-unused identity nodes itself; a subsequent DeadCodeEliminationPass removes them from the FunctionBase.

Example:

Consider a function with a chain of identity operations:

// Original IR snippet
fn simple_ident(x: bits[8]) -> bits[8] {
  one: bits[8] = literal(value=1)
  v1:  bits[8] = identity(x)
  add: bits[8] = add(v1, one)
  v2:  bits[8] = identity(add)
  v3:  bits[8] = identity(v2)
  ret res: bits[8] = sub(v3, one)
}

After IdentityRemovalPass (and DeadCodeEliminationPass to remove the orphaned identity nodes), the IR becomes:

// Optimized IR (after IdentityRemovalPass and DCE)
fn simple_ident(x: bits[8]) -> bits[8] {
  one: bits[8] = literal(value=1)
  add: bits[8] = add(x, one)
  ret res: bits[8] = sub(add, one)
}

Header

inlining - Inlines invocations

Inlines a package toward the top function/proc.

If full then all functions are inlined into the top.

If leaf then only leaf functions are inlined into their caller. This allows other passes to optimize on smaller graphs.

Note

What follows was generated by the Gemini LLM. Not human verified.

The InliningPass replaces invoke operations (function calls) with the body of the invoked function, exposing interprocedural optimization opportunities to intraprocedural passes (such as CSE, narrowing, and DCE) and flattening the call hierarchy for hardware synthesis. Foreign functions (those with ForeignFunctionData for FFI) cannot be inlined and are skipped.

Inlining Depth Modes (InlineDepth):

  1. InlineDepth::kFull (registered as "inlining"): Processes all FunctionBases in the package in post-order of the call graph (FunctionsInPostOrder(p), leaves first) and inlines every non-foreign invoke in each caller where ShouldInlineInto(caller) is true. Processing leaves first guarantees that when a callee is inlined into its caller, any invokes inside that callee have already been inlined, avoiding duplicate work.

  2. InlineDepth::kLeafOnly (registered as "leaf-inlining"): Uses GetFunctionsToInlineByLeaf to inline into a caller f only if every invoke in f targets either: * A leaf function (one that contains zero inlineable invokes), or * A non-leaf function that has only a single inlineable invoke call (to_inline_cnt == 1) and is itself selected for inlining in the same pass. Note that GetFunctionsToInlineByLeaf requires all map and loop constructs (counted_for / dynamic_counted_for) to have been lowered to invokes prior to running.

How InlineInvoke Works:

For each eligible Invoke node:

  1. Parameter Mapping & Topological Cloning: Maps each Param of the callee (invoke->to_apply()) to the corresponding argument operand of the invoke. It then iterates through the callee's nodes in topological order (context.TopoSort(invoked)) and clones each non-parameter node into the caller FunctionBase via CloneInNewFunction.

  2. Source Location Merging: If a cloned node has an empty SourceInfo, it inherits invoke->loc(); otherwise, the SourceLocation entries from invoke->loc() are appended to the cloned node's location list.

  3. Node Name Propagation: * Return Value: If the invoke node has an assigned name, the cloned return value node's name is cleared before ReplaceUsesWith so that it inherits the invoke node's assigned name. * Parameter-Derived Names (GetInlinedNodeName): For any other node in the callee with an assigned name, if its name starts with a callee parameter's name and the corresponding invoke argument also has an assigned name, the longest matching parameter prefix is replaced with the argument's name (e.g., inlining x_neg: neg(x) with argument foo names the cloned node foo_neg).

  4. cover and assert Label Qualification (GetPrefixedLabel): To prevent duplicate Verilog cover/assert property labels when a function is inlined multiple times, any cover node or labeled assert node has its original user label saved in original_label (if not already set) and its active label prefixed with <caller_name>_<inline_count>_<callee_name>_<label>. (A later LabelRecoveryPass can restore original_label when no collisions occur.)

  5. Replacement: All uses of invoke are replaced with the cloned return value node, and the invoke node is removed from the caller.

Example (kFull Inlining):

// Original IR
package some_package

fn callee(x: bits[32], y: bits[32]) -> bits[32] {
  ret add.1: bits[32] = add(x, y)
}

top fn caller() -> bits[32] {
  literal.2: bits[32] = literal(value=2)
  ret invoke.3: bits[32] = invoke(literal.2, literal.2, to_apply=callee)
}

After InliningPass (followed by DeadFunctionEliminationPass to remove the unreferenced callee), invoke.3 is replaced by the cloned add:

// Optimized IR (after Inlining and DFE)
package some_package

top fn caller() -> bits[32] {
  literal.2: bits[32] = literal(value=2)
  ret add.4: bits[32] = add(literal.2, literal.2)
}

Header

invalidate_cached_proc_state_info - Invalidate proc state cached range information.

Helper fake class that invalidates cached proc-state information in the query engines.

This invalidates the givens in PartialInfoQueryEngine and LazyTernaryQueryEngine.

Note

What follows was generated by the Gemini LLM. Not human verified.

InvalidateCachedProcStateInfoPass is a bookkeeping pseudo-pass for Procs that clears cached proc state range and ternary invariants ("givens") stored in the OptimizationContext's shared query engines, without modifying the IR itself.

Background and Motivation:

During proc optimization (such as ProcStateRangeQueryEngine and ProcStateNarrowingPass), XLS analyzes how proc state elements evolve across ticks and records proven state-element invariants in CachedStateElementQueryEngine wrappers around PartialInfoQueryEngine and LazyTernaryQueryEngine. Caching these state invariants allows subsequent passes to retain narrowed state bounds even after intermediate rewrites make the state evolution harder to re-derive from scratch. However, once a group of passes finishes or before transformations that might invalidate those cached assumptions, the cached state "givens" must be explicitly cleared.

How it Works:

When run on a Proc, RunOnProcInternal retrieves both cached query engines from OptimizationContext and clears their recorded state-element givens: 1. CachedStateElementQueryEngine::FromContext<PartialInfoQueryEngine> ->ClearGivens() 2. CachedStateElementQueryEngine::FromContext<LazyTernaryQueryEngine> ->ClearGivens()

The pass always returns false because it only mutates analysis cache state in OptimizationContext and never alters the IR graph.

Example:

Suppose a proc has a 32-bit state element st that ProcStateNarrowingPass proves is always in [0, 7], caching that range in CachedStateElementQueryEngine:

// IR remains unchanged before and after InvalidateCachedProcStateInfoPass;
// only the cached state-element givens in OptimizationContext are cleared.
proc counter(st: bits[32], init={0}) {
  lit1: bits[32] = literal(value=1)
  sum: bits[32] = add(st, lit1)
  mask: bits[32] = literal(value=7)
  next_st: bits[32] = and(sum, mask)
  next (next_st)
}

Header

label-recovery - LabelRecovery

At the end of the pass pipeline (when inlining and optimizations have been performed) attempts to recover original names for coverpoints and assertions to whatever degree possible so they're more human-readable -- we mangle them for inlining to ensure they're unique, but often those names are way overqualified.

Note

What follows was generated by the Gemini LLM. Not human verified.

The LabelRecoveryPass restores human-readable user-defined labels on cover and assert nodes after function inlining and subsequent optimizations have completed. During InliningPass, cover and assert labels are prefixed with caller, inline-count, and callee identifiers (e.g., <caller>_<inline_count>_<callee>_<label>) while preserving the pre-inlined name in the node's original_label attribute. This avoids duplicate property names in generated Verilog when a function is inlined multiple times, but can leave overly verbose labels when only a single instance survives.

How it Works:

  1. Grouping by original_label: The pass scans all nodes in the FunctionBase and collects every cover (Op::kCover) and assert (Op::kAssert) node that has an original_label attribute into a map keyed by original_label (original_label_to_nodes). Note that cover and assert nodes share the same collision map.

  2. Collision-Free Restoration: For each original_label in the map: * Unique Instance (nodes.size() == 1): If only a single cover or assert node in the FunctionBase has that original_label, restoring it cannot cause a label collision. The pass updates the node's active label via set_label(original_label). * Multiple Instances (nodes.size() > 1): If multiple inlined nodes share the same original_label, their mangled labels are kept unchanged so each instance retains a unique identifier.

Example:

Consider a callee function with a cover point that is invoked once by caller:

// IR after InliningPass and DCE (before LabelRecoveryPass)
package p

top fn caller(p: bits[1]) -> () {
  ret cover.1: () = cover(p, label="caller_0_callee_my_cover_label",
                             original_label="my_cover_label")
}

Because cover.1 is the only node in caller with original_label="my_cover_label", LabelRecoveryPass restores its label:

// IR after LabelRecoveryPass
package p

top fn caller(p: bits[1]) -> () {
  ret cover.1: () = cover(p, label="my_cover_label",
                             original_label="my_cover_label")
}

Header

leaf-inlining - Inlines invocations

Inlines a package toward the top function/proc.

If full then all functions are inlined into the top.

If leaf then only leaf functions are inlined into their caller. This allows other passes to optimize on smaller graphs.

Note

What follows was generated by the Gemini LLM. Not human verified.

The InliningPass replaces invoke operations (function calls) with the body of the invoked function, exposing interprocedural optimization opportunities to intraprocedural passes (such as CSE, narrowing, and DCE) and flattening the call hierarchy for hardware synthesis. Foreign functions (those with ForeignFunctionData for FFI) cannot be inlined and are skipped.

Inlining Depth Modes (InlineDepth):

  1. InlineDepth::kFull (registered as "inlining"): Processes all FunctionBases in the package in post-order of the call graph (FunctionsInPostOrder(p), leaves first) and inlines every non-foreign invoke in each caller where ShouldInlineInto(caller) is true. Processing leaves first guarantees that when a callee is inlined into its caller, any invokes inside that callee have already been inlined, avoiding duplicate work.

  2. InlineDepth::kLeafOnly (registered as "leaf-inlining"): Uses GetFunctionsToInlineByLeaf to inline into a caller f only if every invoke in f targets either: * A leaf function (one that contains zero inlineable invokes), or * A non-leaf function that has only a single inlineable invoke call (to_inline_cnt == 1) and is itself selected for inlining in the same pass. Note that GetFunctionsToInlineByLeaf requires all map and loop constructs (counted_for / dynamic_counted_for) to have been lowered to invokes prior to running.

How InlineInvoke Works:

For each eligible Invoke node:

  1. Parameter Mapping & Topological Cloning: Maps each Param of the callee (invoke->to_apply()) to the corresponding argument operand of the invoke. It then iterates through the callee's nodes in topological order (context.TopoSort(invoked)) and clones each non-parameter node into the caller FunctionBase via CloneInNewFunction.

  2. Source Location Merging: If a cloned node has an empty SourceInfo, it inherits invoke->loc(); otherwise, the SourceLocation entries from invoke->loc() are appended to the cloned node's location list.

  3. Node Name Propagation: * Return Value: If the invoke node has an assigned name, the cloned return value node's name is cleared before ReplaceUsesWith so that it inherits the invoke node's assigned name. * Parameter-Derived Names (GetInlinedNodeName): For any other node in the callee with an assigned name, if its name starts with a callee parameter's name and the corresponding invoke argument also has an assigned name, the longest matching parameter prefix is replaced with the argument's name (e.g., inlining x_neg: neg(x) with argument foo names the cloned node foo_neg).

  4. cover and assert Label Qualification (GetPrefixedLabel): To prevent duplicate Verilog cover/assert property labels when a function is inlined multiple times, any cover node or labeled assert node has its original user label saved in original_label (if not already set) and its active label prefixed with <caller_name>_<inline_count>_<callee_name>_<label>. (A later LabelRecoveryPass can restore original_label when no collisions occur.)

  5. Replacement: All uses of invoke are replaced with the cloned return value node, and the invoke node is removed from the caller.

Example (kFull Inlining):

// Original IR
package some_package

fn callee(x: bits[32], y: bits[32]) -> bits[32] {
  ret add.1: bits[32] = add(x, y)
}

top fn caller() -> bits[32] {
  literal.2: bits[32] = literal(value=2)
  ret invoke.3: bits[32] = invoke(literal.2, literal.2, to_apply=callee)
}

After InliningPass (followed by DeadFunctionEliminationPass to remove the unreferenced callee), invoke.3 is replaced by the cloned add:

// Optimized IR (after Inlining and DFE)
package some_package

top fn caller() -> bits[32] {
  literal.2: bits[32] = literal(value=2)
  ret add.4: bits[32] = add(literal.2, literal.2)
}

Header

loop_unroll - Unroll counted loops

Note

What follows was generated by the Gemini LLM. Not human verified.

The UnrollPass unrolls counted_for loops within a function or proc by expanding each iteration into an explicit invoke of the loop's body function.

How it Works:

  1. Loop Discovery: The pass searches the FunctionBase for any effectively used counted_for node (a node that has users or is the function return value).
  2. Iterative Expansion: For a counted_for with trip_count iterations and step stride, the pass initializes the loop-carried accumulator loop_carry to initial_value. For each trip 0 <= trip < trip_count (with induction variable iv = trip * stride), it: * Creates a literal node for iv matching the bit-width of the body function's first parameter. * Emits an invoke node calling body with arguments [iv, loop_carry, invariant_args...] and updates loop_carry to the result of the invoke.
  3. Replacement: All uses of the counted_for node are replaced with the final loop_carry node (or initial_value if trip_count == 0), and the counted_for node is removed. This repeats until no used counted_for nodes remain.

Example:

// Original IR
fn body(i: bits[4], accum: bits[32], zero: bits[32]) -> bits[32] {
  zero_ext.3: bits[32] = zero_ext(i, new_bit_count=32)
  add.4: bits[32] = add(zero_ext.3, accum)
  ret add.5: bits[32] = add(add.4, zero)
}

fn unrollable() -> bits[32] {
  literal.1: bits[32] = literal(value=0)
  ret counted_for.2: bits[32] = counted_for(literal.1, trip_count=2,
      stride=2, body=body, invariant_args=[literal.1])
}

// Optimized IR
fn unrollable() -> bits[32] {
  literal.1: bits[32] = literal(value=0)
  literal.6: bits[4] = literal(value=0)
  invoke.7: bits[32] = invoke(literal.6, literal.1, literal.1, to_apply=body)
  literal.8: bits[4] = literal(value=2)
  ret invoke.9: bits[32] = invoke(literal.8, invoke.7, literal.1,
      to_apply=body)
}

Header

lut_conversion - LUT Conversion

Pass which opportunistically converts nodes to lookup tables (selects) where we can prove it's beneficial.

Note

What follows was generated by the Gemini LLM. Not human verified.

The LutConversionPass absorbs combinational logic feeding the selector of one or more select operations into the select operations themselves, converting them into direct lookup tables (LUTs) indexed by a smaller or simpler cut of ancestor bits.

The pass is gated on options.narrowing_enabled() and uses a UnionQueryEngine combining StatelessQueryEngine and a shared LazyTernaryQueryEngine.

How it Works:

  1. Candidate Discovery (ComputeLutConversionCandidates): The pass traverses nodes in reverse topological order (context.ReverseTopoSort(func)), skipping dead nodes. For each node that serves as the selector() of at least one Select user: * It computes the maximum number of cases (max_case_count, counting default_value as an extra case if present) across all Select users controlled by this selector, and determines the maximum bit width required to index them: max_bits_needed = Bits::MinBitCountUnsigned(max_case_count - 1). Selectors with max_bits_needed <= 1 are skipped. * Using DataflowGraphAnalysis::GetMinCutFor, it finds a minimum cut (min_cut) of ancestor nodes that completely determine the selector's value with at most max_bits_needed total unknown bits (unknown_bits) according to the ternary query engine. * It checks whether the selector is already trivially derived from min_cut (IsTriviallyDerived, meaning constructed only from min_cut nodes and literals via tuple_index, bit_slice, literal-indexed array_index, and concat). * Each controlled Select user (requiring bits_needed selector bits) is kept as a candidate user if either: * unknown_bits < bits_needed (the LUT conversion strictly narrows the Select), or * unknown_bits == bits_needed && !selector_is_trivial (the Select stays the same width, but non-trivial combinational selector logic is absorbed into the LUT, reducing delay).

  2. Truth-Table Evaluation (ComputeLutSelectCases): * An IrInterpreter is pre-populated with all statically known node values (query_engine.KnownValue(n)) in the cone feeding the selector. * For each node in min_cut, all concrete Values compatible with its TernaryVector are enumerated (ternary_ops::AllValues). * MixedRadixIterate iterates over all combinations of min_cut values (with earlier min_cut nodes varying fastest, corresponding to lower-order bits of the new selector) and evaluates the original selector node in the IrInterpreter to record the sequence of selected case indices (new_case_sequence).

  3. Merging into Controlled Selects (MergeLutIntoSelects): * Single-Case Fold: If every combination in new_case_sequence selects the exact same case index, each controlled Select is replaced directly by that single case node. * New Select Construction: Otherwise, for each node in min_cut, the pass extracts its unknown bits using GatherBits, reverses the pieces so earlier min_cut nodes occupy the least-significant bits, and concatenates them into new_selector. Each controlled Select is then replaced with a new Select(new_selector, new_cases, /*default_value=*/std::nullopt) whose cases are permuted/selected from the original Select according to new_case_sequence.

Example:

Consider a select whose selector doubled_x is a non-trivial arithmetic function (add(x, x)) of a 2-bit input x:

// Original IR snippet
fn simple_select(x: bits[2], a: bits[8], b: bits[8], c: bits[8]) -> bits[8] {
  doubled_x: bits[2] = add(x, x)
  ret result: bits[8] = sel(doubled_x, cases=[a, b, c], default=a)
}

DataflowGraphAnalysis finds min_cut = {x} with unknown_bits = 2, which matches bits_needed = 2 for the 4-way sel while eliminating the add from the selector path. Evaluating doubled_x for x = 0, 1, 2, 3 yields selector values 0, 2, 0, 2, producing:

// Optimized IR (after LutConversionPass and DCE)
fn simple_select(x: bits[2], a: bits[8], b: bits[8], c: bits[8]) -> bits[8] {
  ret result: bits[8] = sel(x, cases=[a, c, a, c])
}

Header

map_inlining - Inline map operations

A pass to convert map nodes to in-line Invoke nodes. We don't directly lower maps to Verilog.

Note

What follows was generated by the Gemini LLM. Not human verified.

The MapInliningPass lowers map operations (Op::kMap) in a FunctionBase into explicit per-element array_index and invoke operations assembled into an array. Because hardware description languages like Verilog do not directly represent higher-order map operations, this pass unrolls them so that subsequent InliningPass and optimization passes can inline and optimize the applied function across all array elements.

How it Works:

  1. Collecting map Nodes: The pass scans function->nodes() and collects all Map nodes.
  2. Unrolling (ReplaceMap): For each map node with input array map->operand(0) of size N and target function map->to_apply(): * For each element index i from 0 to N - 1: * Creates a Literal node index with value UBits(i, Bits::MinBitCountUnsigned(N)). * Creates an ArrayIndex node extracting element i from map->operand(0). * Creates an Invoke node applying map->to_apply() to that ArrayIndex element. * Replaces all uses of map with a new Array node containing the N Invoke results, and removes the original map node from the FunctionBase.

A static helper MapInliningPass::InlineOneMap(Map* map) is also provided for testing and ir_minimizer use.

Example:

Consider a map operation that applies map_fn to a 4-element array a:

fn map_fn(x: bits[32]) -> bits[16] {
  ret bit_slice.1: bits[16] = bit_slice(x, start=0, width=16)
}

fn main(a: bits[32][4]) -> bits[16][4] {
  ret result: bits[16][4] = map(a, to_apply=map_fn)
}

After MapInliningPass, the map node is replaced by an array of four invoke operations:

fn map_fn(x: bits[32]) -> bits[16] {
  ret bit_slice.1: bits[16] = bit_slice(x, start=0, width=16)
}

fn main(a: bits[32][4]) -> bits[16][4] {
  literal.2: bits[3] = literal(value=0)
  array_index.3: bits[32] = array_index(a, indices=[literal.2])
  invoke.4: bits[16] = invoke(array_index.3, to_apply=map_fn)
  literal.5: bits[3] = literal(value=1)
  array_index.6: bits[32] = array_index(a, indices=[literal.5])
  invoke.7: bits[16] = invoke(array_index.6, to_apply=map_fn)
  literal.8: bits[3] = literal(value=2)
  array_index.9: bits[32] = array_index(a, indices=[literal.8])
  invoke.10: bits[16] = invoke(array_index.9, to_apply=map_fn)
  literal.11: bits[3] = literal(value=3)
  array_index.12: bits[32] = array_index(a, indices=[literal.11])
  invoke.13: bits[16] = invoke(array_index.12, to_apply=map_fn)
  ret array.14: bits[16][4] =
      array(invoke.4, invoke.7, invoke.10, invoke.13)
}

Header

name_promotion - Name Promotion

Promotes nodes whose assigned names were uniquified by the NameUniquer back to their originally requested names if those names have since become available (for example, because the colliding node was removed by dead code elimination).

Note

What follows was generated by the Gemini LLM. Not human verified.

When multiple nodes in a FunctionBase request the same name foo, the NameUniquer assigns foo to the first node and uniquified names such as foo__1, foo__2, etc. to subsequent nodes, while recording that their originally requested name was foo. During optimization, the original node named foo (or an intermediate node in a collision chain) is often replaced or deleted by dead code elimination (DeadCodeEliminationPass), releasing foo in the FunctionBase's NameUniquer.

NamePromotionPass scans the nodes of a FunctionBase and promotes any eligible node whose originally requested name is now free back to that original name. The pass iterates to a fixed point so that cascading promotions (e.g., promoting foo__1 to foo frees foo__1 for a node that originally requested foo__1 and received foo__2) are resolved in a single pass invocation. Parameter and port nodes are never renamed.

Header

narrow - Narrowing

A pass which reduces the width of operations eliminating redundant or unused bits.

Note

What follows was generated by the Gemini LLM. Not human verified.

The NarrowingPass is a powerful optimization pass in XLS designed to reduce the bit width of bits-typed operations and values within a function or proc. This is a critical optimization for hardware generation, as a reduction in bit widths directly translates to smaller, more efficient, and often faster hardware (fewer wires, smaller functional units, and smaller registers). The pass employs various advanced analysis techniques to determine the minimum required bit width for each value without altering its functional correctness.

The pass is configured with an AnalysisType enum, which dictates the sophistication of the analysis used:

  • kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
  • kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
  • kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) of select operations and other conditional control flow to derive more precise ranges for values within specific execution paths.
  • kRangeWithOptionalContext: Allows the choice between kRange and kRangeWithContext based on the options.use_context_narrowing_analysis flag, providing flexibility in trade-off between analysis time and precision.

The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:

  1. Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a literal node. This simplifies the graph and can enable further optimizations.

  2. Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (eq, ne, ult, ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.

      ```
      // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings
      // Leading `0110` and trailing `0011` match for both operands.
      // Optimized: UGt(0bXXX, 0bYYY)
      ```
    

    * Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.

  3. Narrowing Negate Operations: * Trailing Zeros: If an operand to a negate operation has known trailing zeros, the negate can be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of the negate operation.

    * Sign Extension Hoisting: For negate(sign_ext(x)), if the range analysis shows that x cannot be the minimum representable signed value, this can be simplified to sign_ext(negate(x)), reducing the width of the negate operation. More generally, it finds the minimal bit width for the inner negate and then re-extends.

  4. Narrowing Shift Operations (shll, shra, shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).

    * Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the shift_value are known to be zero or sign bits, the shift_value can be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. The shift_amount itself can also be narrowed if it has leading zeros.

    * Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.

  5. Narrowing Add and Sub Operations: * Common Leading Zeros/Sign Bits: For add and sub operations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions.

  6. Narrowing Multiply Operations (umul, smul, umulp, smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.

    * Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.

    * Extended Operands (Zero-extend/Sign-extend): When operands are the results of zero_ext or sign_ext operations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g., umul or smul) if necessary to maintain correctness.

    * Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.

    * Partial Product Optimization: For umulp/smulp (partial product multiplies), if the two partial products are immediately summed (e.g., add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended.

  7. Narrowing ArrayIndex Operations: * Literal Index Values: If an index to an array_index is a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.

    * Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.

    * Known Out-of-Bounds Index: Similar to BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.

    * Convert ArrayIndex to Select: For array_index operations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to a select chain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic.

  8. Narrowing Decode Operations: * Leading Zeros in Index: If the index of a decode operation has leading zeros, the index can be sliced to remove them, and the decode performed on the narrower index, with the result zero-extended if needed.

    * Zero Index: A decode with a provably zero index is replaced by a literal one, as decode(0) always results in a one-hot encoding with the least significant bit set.

The NarrowingPass is typically run repeatedly within an optimization pipeline until a fixed point is reached. This iterative process is crucial for achieving maximal bit width reduction across the entire IR, as narrowing one node can often enable further narrowing of its consumers or producers.

Header

narrow(Context) - Narrowing

A pass which reduces the width of operations eliminating redundant or unused bits.

Note

What follows was generated by the Gemini LLM. Not human verified.

The NarrowingPass is a powerful optimization pass in XLS designed to reduce the bit width of bits-typed operations and values within a function or proc. This is a critical optimization for hardware generation, as a reduction in bit widths directly translates to smaller, more efficient, and often faster hardware (fewer wires, smaller functional units, and smaller registers). The pass employs various advanced analysis techniques to determine the minimum required bit width for each value without altering its functional correctness.

The pass is configured with an AnalysisType enum, which dictates the sophistication of the analysis used:

  • kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
  • kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
  • kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) of select operations and other conditional control flow to derive more precise ranges for values within specific execution paths.
  • kRangeWithOptionalContext: Allows the choice between kRange and kRangeWithContext based on the options.use_context_narrowing_analysis flag, providing flexibility in trade-off between analysis time and precision.

The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:

  1. Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a literal node. This simplifies the graph and can enable further optimizations.

  2. Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (eq, ne, ult, ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.

      ```
      // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings
      // Leading `0110` and trailing `0011` match for both operands.
      // Optimized: UGt(0bXXX, 0bYYY)
      ```
    

    * Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.

  3. Narrowing Negate Operations: * Trailing Zeros: If an operand to a negate operation has known trailing zeros, the negate can be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of the negate operation.

    * Sign Extension Hoisting: For negate(sign_ext(x)), if the range analysis shows that x cannot be the minimum representable signed value, this can be simplified to sign_ext(negate(x)), reducing the width of the negate operation. More generally, it finds the minimal bit width for the inner negate and then re-extends.

  4. Narrowing Shift Operations (shll, shra, shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).

    * Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the shift_value are known to be zero or sign bits, the shift_value can be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. The shift_amount itself can also be narrowed if it has leading zeros.

    * Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.

  5. Narrowing Add and Sub Operations: * Common Leading Zeros/Sign Bits: For add and sub operations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions.

  6. Narrowing Multiply Operations (umul, smul, umulp, smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.

    * Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.

    * Extended Operands (Zero-extend/Sign-extend): When operands are the results of zero_ext or sign_ext operations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g., umul or smul) if necessary to maintain correctness.

    * Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.

    * Partial Product Optimization: For umulp/smulp (partial product multiplies), if the two partial products are immediately summed (e.g., add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended.

  7. Narrowing ArrayIndex Operations: * Literal Index Values: If an index to an array_index is a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.

    * Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.

    * Known Out-of-Bounds Index: Similar to BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.

    * Convert ArrayIndex to Select: For array_index operations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to a select chain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic.

  8. Narrowing Decode Operations: * Leading Zeros in Index: If the index of a decode operation has leading zeros, the index can be sliced to remove them, and the decode performed on the narrower index, with the result zero-extended if needed.

    * Zero Index: A decode with a provably zero index is replaced by a literal one, as decode(0) always results in a one-hot encoding with the least significant bit set.

The NarrowingPass is typically run repeatedly within an optimization pipeline until a fixed point is reached. This iterative process is crucial for achieving maximal bit width reduction across the entire IR, as narrowing one node can often enable further narrowing of its consumers or producers.

Header

narrow(OptionalContext) - Narrowing

A pass which reduces the width of operations eliminating redundant or unused bits.

Note

What follows was generated by the Gemini LLM. Not human verified.

The NarrowingPass is a powerful optimization pass in XLS designed to reduce the bit width of bits-typed operations and values within a function or proc. This is a critical optimization for hardware generation, as a reduction in bit widths directly translates to smaller, more efficient, and often faster hardware (fewer wires, smaller functional units, and smaller registers). The pass employs various advanced analysis techniques to determine the minimum required bit width for each value without altering its functional correctness.

The pass is configured with an AnalysisType enum, which dictates the sophistication of the analysis used:

  • kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
  • kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
  • kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) of select operations and other conditional control flow to derive more precise ranges for values within specific execution paths.
  • kRangeWithOptionalContext: Allows the choice between kRange and kRangeWithContext based on the options.use_context_narrowing_analysis flag, providing flexibility in trade-off between analysis time and precision.

The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:

  1. Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a literal node. This simplifies the graph and can enable further optimizations.

  2. Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (eq, ne, ult, ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.

      ```
      // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings
      // Leading `0110` and trailing `0011` match for both operands.
      // Optimized: UGt(0bXXX, 0bYYY)
      ```
    

    * Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.

  3. Narrowing Negate Operations: * Trailing Zeros: If an operand to a negate operation has known trailing zeros, the negate can be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of the negate operation.

    * Sign Extension Hoisting: For negate(sign_ext(x)), if the range analysis shows that x cannot be the minimum representable signed value, this can be simplified to sign_ext(negate(x)), reducing the width of the negate operation. More generally, it finds the minimal bit width for the inner negate and then re-extends.

  4. Narrowing Shift Operations (shll, shra, shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).

    * Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the shift_value are known to be zero or sign bits, the shift_value can be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. The shift_amount itself can also be narrowed if it has leading zeros.

    * Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.

  5. Narrowing Add and Sub Operations: * Common Leading Zeros/Sign Bits: For add and sub operations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions.

  6. Narrowing Multiply Operations (umul, smul, umulp, smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.

    * Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.

    * Extended Operands (Zero-extend/Sign-extend): When operands are the results of zero_ext or sign_ext operations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g., umul or smul) if necessary to maintain correctness.

    * Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.

    * Partial Product Optimization: For umulp/smulp (partial product multiplies), if the two partial products are immediately summed (e.g., add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended.

  7. Narrowing ArrayIndex Operations: * Literal Index Values: If an index to an array_index is a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.

    * Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.

    * Known Out-of-Bounds Index: Similar to BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.

    * Convert ArrayIndex to Select: For array_index operations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to a select chain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic.

  8. Narrowing Decode Operations: * Leading Zeros in Index: If the index of a decode operation has leading zeros, the index can be sliced to remove them, and the decode performed on the narrower index, with the result zero-extended if needed.

    * Zero Index: A decode with a provably zero index is replaced by a literal one, as decode(0) always results in a one-hot encoding with the least significant bit set.

The NarrowingPass is typically run repeatedly within an optimization pipeline until a fixed point is reached. This iterative process is crucial for achieving maximal bit width reduction across the entire IR, as narrowing one node can often enable further narrowing of its consumers or producers.

Header

narrow(Range) - Narrowing

A pass which reduces the width of operations eliminating redundant or unused bits.

Note

What follows was generated by the Gemini LLM. Not human verified.

The NarrowingPass is a powerful optimization pass in XLS designed to reduce the bit width of bits-typed operations and values within a function or proc. This is a critical optimization for hardware generation, as a reduction in bit widths directly translates to smaller, more efficient, and often faster hardware (fewer wires, smaller functional units, and smaller registers). The pass employs various advanced analysis techniques to determine the minimum required bit width for each value without altering its functional correctness.

The pass is configured with an AnalysisType enum, which dictates the sophistication of the analysis used:

  • kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
  • kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
  • kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) of select operations and other conditional control flow to derive more precise ranges for values within specific execution paths.
  • kRangeWithOptionalContext: Allows the choice between kRange and kRangeWithContext based on the options.use_context_narrowing_analysis flag, providing flexibility in trade-off between analysis time and precision.

The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:

  1. Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a literal node. This simplifies the graph and can enable further optimizations.

  2. Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (eq, ne, ult, ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.

      ```
      // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings
      // Leading `0110` and trailing `0011` match for both operands.
      // Optimized: UGt(0bXXX, 0bYYY)
      ```
    

    * Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.

  3. Narrowing Negate Operations: * Trailing Zeros: If an operand to a negate operation has known trailing zeros, the negate can be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of the negate operation.

    * Sign Extension Hoisting: For negate(sign_ext(x)), if the range analysis shows that x cannot be the minimum representable signed value, this can be simplified to sign_ext(negate(x)), reducing the width of the negate operation. More generally, it finds the minimal bit width for the inner negate and then re-extends.

  4. Narrowing Shift Operations (shll, shra, shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).

    * Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the shift_value are known to be zero or sign bits, the shift_value can be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. The shift_amount itself can also be narrowed if it has leading zeros.

    * Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.

  5. Narrowing Add and Sub Operations: * Common Leading Zeros/Sign Bits: For add and sub operations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions.

  6. Narrowing Multiply Operations (umul, smul, umulp, smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.

    * Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.

    * Extended Operands (Zero-extend/Sign-extend): When operands are the results of zero_ext or sign_ext operations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g., umul or smul) if necessary to maintain correctness.

    * Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.

    * Partial Product Optimization: For umulp/smulp (partial product multiplies), if the two partial products are immediately summed (e.g., add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended.

  7. Narrowing ArrayIndex Operations: * Literal Index Values: If an index to an array_index is a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.

    * Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.

    * Known Out-of-Bounds Index: Similar to BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.

    * Convert ArrayIndex to Select: For array_index operations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to a select chain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic.

  8. Narrowing Decode Operations: * Leading Zeros in Index: If the index of a decode operation has leading zeros, the index can be sliced to remove them, and the decode performed on the narrower index, with the result zero-extended if needed.

    * Zero Index: A decode with a provably zero index is replaced by a literal one, as decode(0) always results in a one-hot encoding with the least significant bit set.

The NarrowingPass is typically run repeatedly within an optimization pipeline until a fixed point is reached. This iterative process is crucial for achieving maximal bit width reduction across the entire IR, as narrowing one node can often enable further narrowing of its consumers or producers.

Header

narrow(Ternary) - Narrowing

A pass which reduces the width of operations eliminating redundant or unused bits.

Note

What follows was generated by the Gemini LLM. Not human verified.

The NarrowingPass is a powerful optimization pass in XLS designed to reduce the bit width of bits-typed operations and values within a function or proc. This is a critical optimization for hardware generation, as a reduction in bit widths directly translates to smaller, more efficient, and often faster hardware (fewer wires, smaller functional units, and smaller registers). The pass employs various advanced analysis techniques to determine the minimum required bit width for each value without altering its functional correctness.

The pass is configured with an AnalysisType enum, which dictates the sophistication of the analysis used:

  • kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
  • kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
  • kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) of select operations and other conditional control flow to derive more precise ranges for values within specific execution paths.
  • kRangeWithOptionalContext: Allows the choice between kRange and kRangeWithContext based on the options.use_context_narrowing_analysis flag, providing flexibility in trade-off between analysis time and precision.

The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:

  1. Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a literal node. This simplifies the graph and can enable further optimizations.

  2. Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (eq, ne, ult, ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.

      ```
      // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings
      // Leading `0110` and trailing `0011` match for both operands.
      // Optimized: UGt(0bXXX, 0bYYY)
      ```
    

    * Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.

  3. Narrowing Negate Operations: * Trailing Zeros: If an operand to a negate operation has known trailing zeros, the negate can be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of the negate operation.

    * Sign Extension Hoisting: For negate(sign_ext(x)), if the range analysis shows that x cannot be the minimum representable signed value, this can be simplified to sign_ext(negate(x)), reducing the width of the negate operation. More generally, it finds the minimal bit width for the inner negate and then re-extends.

  4. Narrowing Shift Operations (shll, shra, shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).

    * Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the shift_value are known to be zero or sign bits, the shift_value can be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. The shift_amount itself can also be narrowed if it has leading zeros.

    * Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.

  5. Narrowing Add and Sub Operations: * Common Leading Zeros/Sign Bits: For add and sub operations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions.

  6. Narrowing Multiply Operations (umul, smul, umulp, smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.

    * Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.

    * Extended Operands (Zero-extend/Sign-extend): When operands are the results of zero_ext or sign_ext operations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g., umul or smul) if necessary to maintain correctness.

    * Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.

    * Partial Product Optimization: For umulp/smulp (partial product multiplies), if the two partial products are immediately summed (e.g., add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended.

  7. Narrowing ArrayIndex Operations: * Literal Index Values: If an index to an array_index is a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.

    * Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.

    * Known Out-of-Bounds Index: Similar to BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.

    * Convert ArrayIndex to Select: For array_index operations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to a select chain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic.

  8. Narrowing Decode Operations: * Leading Zeros in Index: If the index of a decode operation has leading zeros, the index can be sliced to remove them, and the decode performed on the narrower index, with the result zero-extended if needed.

    * Zero Index: A decode with a provably zero index is replaced by a literal one, as decode(0) always results in a one-hot encoding with the least significant bit set.

The NarrowingPass is typically run repeatedly within an optimization pipeline until a fixed point is reached. This iterative process is crucial for achieving maximal bit width reduction across the entire IR, as narrowing one node can often enable further narrowing of its consumers or producers.

Header

next_value_opt - Next Value Optimization

Pass which tries to optimize next_value nodes within a Proc.

Note

What follows was generated by the Gemini LLM. Not human verified.

NextValueOptimizationPass simplifies next_value state update nodes in a Proc and exposes opportunities for downstream passes such as narrowing, constant folding, and dead code elimination.

Optimizations

  1. Removing Constant Predicates: Using StatelessQueryEngine, if a next_value node has a predicate operand whose value is known to be a constant:

    • Constant 0 (false): The next_value never fires and is removed.
    • Constant 1 (true): The predicate operand is removed, making the next_value unconditional.

    Example (removing a dead next_value):

    // Before
    f: bits[1] = literal(value=0)
    next_v: () = next_value(state_element=x, value=my_value, predicate=f)
    
    // After
    // (next_v is removed)
    
  2. Splitting Select-Based Values: When options.splits_enabled() is true and max_split_depth > 0 (default kDefaultMaxSplitDepth = 10), a next_value whose value operand is a select operation can be split into separate next_value nodes for each case (and default case, if present). Each new next_value is predicated on the conjunction (and) of the original next_value predicate (if any) and the condition selecting that case:

    • sel (Select): Split only if options.split_next_value_selects (default kDefaultSplitNextValueSelects = 4) is set and the number of cases is at most *options.split_next_value_selects.
    • priority_sel (PrioritySelect): Always eligible for splitting up to max_split_depth.
    • one_hot_sel (OneHotSelect): Split only if StatelessQueryEngine proves ExactlyOneBitTrue(selector).

    Newly split next_value nodes are pushed back onto the worklist so they can undergo constant-predicate removal or further recursive select splitting up to max_split_depth.

    Example (splitting a sel):

    // Before
    s: bits[2] = state_read(state_element=x)
    c0: bits[2] = literal(value=2)
    c1: bits[2] = literal(value=1)
    def: bits[2] = literal(value=3)
    next_val: bits[2] = sel(s, cases=[c0, c1], default=def)
    next_v: () = next_value(state_element=x, value=next_val)
    
    // After
    s: bits[2] = state_read(state_element=x)
    c0: bits[2] = literal(value=2)
    c1: bits[2] = literal(value=1)
    def: bits[2] = literal(value=3)
    zero: bits[2] = literal(value=0)
    one: bits[2] = literal(value=1)
    max_case: bits[2] = literal(value=1)
    is_0: bits[1] = eq(s, zero)
    is_1: bits[1] = eq(s, one)
    is_def: bits[1] = ugt(s, max_case)
    next_v_case_0: () = next_value(state_element=x, value=c0, predicate=is_0)
    next_v_case_1: () = next_value(state_element=x, value=c1, predicate=is_1)
    next_v_def: () = next_value(state_element=x, value=def, predicate=is_def)
    
  3. Decoupling Equivalent Non-Synthesizable State Elements: NonSynthSeparationPass duplicates state elements read by non-synthesizable operations into non_synthesizable state elements with identical initial values and next_value updates. Before processing the worklist, this pass snapshots each state element's initial value and sorted pre-pass (value, predicate) next_value list. When splitting a select on a next_value for a non_synthesizable state element, any branch (case or default) whose value is a state_read of a synthesizable state element with an identical pre-pass snapshot is rewritten to a state_read of that non_synthesizable state element with a matching predicate (if one exists). Because matching compares pre-pass snapshots rather than pairing elements 1-to-1, non-synthesizable updates are rewritten even when multiple synthesizable and non_synthesizable state elements share identical transitions, decoupling the synthesizable state_read from non-synthesizable pass-through updates so ConditionalSpecializationPass can predicate the synthesizable state_read.

Header

non_synth_separation - Non-Synthesizable Separation

Separates out non-synthesizable nodes like assert/cover/trace from the main function into a cloned function. Every function effectively has two versions, one with synthesizable nodes and one without. The synthesizable version invokes the non-synthesizable version of its function. This ensures that non-synthesizable uses of values do not affect the optimization of the synthesizable parts of the function.

Note

What follows was generated by the Gemini LLM. Not human verified.

NonSynthSeparationPass isolates non-synthesizable operations (assert, cover, and trace) from the synthesizable logic of each function or proc in a package. Without this separation, values consumed by verification or debugging operations appear live to passes like Dead Code Elimination (DCE) or Proc state narrowing/elimination, preventing those passes from optimizing the synthesizable hardware path.

How It Works

  1. Identification: The pass inspects each FunctionBase in the package. If a function or proc contains no assert, cover, or trace nodes, it is left unchanged.

  2. Cloning into a #[non_synth] Function: For each function or proc containing non-synthesizable nodes, a new function named non_synth_<name> (uniquified if needed) is created and marked with set_non_synth(true):

    • For a Function: The function is cloned directly with the same parameters. Its return value is replaced with an empty tuple tuple(), and an invoke to non_synth_<name> (passing the function's parameters) is inserted into the original function.
    • For a Proc: The proc body is cloned into a stateless Function via CloneProcAsFunctionVisitor, converting proc-specific constructs so they can be passed as arguments to an invoke in the proc:
      • Send: Bypassed in the cloned function by mapping the send node directly to its mapped input token.
      • Receive: The token at tuple index 0 is sliced out (SliceTuple) in the proc, and the remaining payload elements are passed as an argument to the invoke (becoming a Param in the cloned function, where the mapped token is spliced back in at index 0).
      • StateRead: Pure token state reads are replaced with literal(token) in the cloned function. For non-token state elements, the pass appends a duplicate state element <state>_non_synth marked non_synthesizable=true (with the same initial value) and a corresponding state_read in the proc, passing that read into the invoke. If the state type contains tokens, token leaf elements are stripped before the invoke and replaced with fresh literal(token) nodes inside the cloned function.
      • Next: Not copied into the cloned function; instead, for each non-token next_value in the proc, a matching next_value node is added to update the <state>_non_synth state element.
  3. Gate-to-Select Conversion in the Non-Synthesizable Function: Any gate(cond, data) operations inside non_synth_<name> are replaced with sel(cond, cases=[data], default=0) (ReplaceGatesWithSelectsVisitor). Because gate nodes are special power-optimization nodes that DCE does not remove, converting them to sel prevents unnecessary gate duplication and allows unused logic in the non-synthesizable function to be optimized away.

  4. Stripping Non-Synthesizable Nodes from the Original Function/Proc: RemoveNonSynthNodesVisitor removes all assert, trace, and cover nodes from the original FunctionBase (replacing assert and trace uses with their input token operand and cover uses with tuple()).

Example

// Before
fn my_func(x: bits[32]) -> bits[32] {
  tok: token = literal(value=token)
  intermediate: bits[32] = add(x, literal(value=1, bits=32))
  is_zero: bits[1] = eq(intermediate, literal(value=0, bits=32))
  assert.1: token = assert(tok, is_zero, message="intermediate is zero!")
  ret result: bits[32] = umul(intermediate, literal(value=2, bits=32))
}

After NonSynthSeparationPass (and subsequent DCE cleanup):

// Synthesizable version (original function, modified)
fn my_func(x: bits[32]) -> bits[32] {
  intermediate: bits[32] = add(x, literal(value=1, bits=32))
  invoke.1: () = invoke(x, to_apply=non_synth_my_func)
  ret result: bits[32] = umul(intermediate, literal(value=2, bits=32))
}

// Non-synthesizable version (newly created function)
#[non_synth]
fn non_synth_my_func(x: bits[32]) -> () {
  tok: token = literal(value=token)
  intermediate: bits[32] = add(x, literal(value=1, bits=32))
  is_zero: bits[1] = eq(intermediate, literal(value=0, bits=32))
  assert.1: token = assert(tok, is_zero, message="intermediate is zero!")
  ret tuple.1: () = tuple()
}

Header

one-leaf-inlining - leaf function inlining passes

inline one level of functions.

Text-proto

Invoked Passes

post-inlining - Post-inlining passes

Passes performed after inlining

Text-proto

Invoked Passes

post-inlining-opt - post-inlining optimization passes

Passes performed after inlining

Text-proto

Invoked Passes

post-inlining-opt(>=1) - min-1 post-inlining optimization passes

Passes performed after inlining

Text-proto

Options Set

Min opt level: 1

Invoked Passes

pre-inlining - pre-inlining passes

Passes performed before each inlining.

Text-proto

Invoked Passes

prepare-for-scheduling - Prepare for scheduling optimization passes

Passes performed at the very end of optimization.

TODO(allight): We might want to move resource sharing into here fororganizational reasons.

TODO(allight): The duplication between this and scheduling-opt is a massive code-smell. Significant adjustments to codegen/sched pass pipelines are likely required.

Text-proto

Options Set

Min opt level: 1

Invoked Passes

proc_state_array_flat - Proc State Array Flattening

Pass which flattens array elements of the proc state into their constituent elements. Tuples are flattened in a different pass. Flattening improves optimizability because each state element can be considered and transformed in isolation. Flattening also gives the scheduler more flexibility; without flattening, each element in the aggregate must have the same lifetime.

Note

What follows was generated by the Gemini LLM. Not human verified.

ProcStateArrayFlatteningPass converts small array-typed StateElements in a Proc into tuple-typed StateElements of their constituent elements, relying on a subsequent ProcStateTupleFlatteningPass to decompose those tuples into independent state elements.

Breaking array state elements apart allows downstream passes (such as state narrowing, constant propagation, and dead state elimination) to optimize each array slot independently, and frees the scheduler from forcing all elements of the array to share an identical register lifetime.

How It Works

  1. Flattening Heuristic (ShouldFlattenStateElement): The pass inspects each array-typed StateElement owned by the Proc and flattens it if its array size is at most 2 (size() <= 2). (Although kMaxArrayFlattenSize is defined on the class, the current implementation only flattens arrays of length 2 or smaller.)
  2. State Element Conversion (ArrayToTupleStateTransformer): Using Proc::TransformStateElement, an array state element of type T[N] with initial value [v_0, ..., v_{N-1}] is replaced by a tuple state element of type (T, ..., T) with initial value (v_0, ..., v_{N-1}):
    • Transforming StateReads: Uses of the old array StateRead are replaced with an array node (<old_state_read>_as_array) constructed from tuple_index(new_state_read, i) for i = 0 .. N-1.
    • Transforming Next Values: For each next_value targeting the state element, its array-typed value operand v is converted into a tuple node (<v>_as_tuple) whose elements are extracted via array_index(v, indices=[literal(i)]) (using index bit width max(1, CeilOfLog2(N))).
  3. Cleanup: The old next_value nodes and the original array-typed StateElement are removed from the Proc.

Example

// Before
proc my_proc(s: bits[8][2], init={[0, 1]}) {
  s_read: bits[8][2] = state_read(state_element=s)
  idx0: bits[1] = literal(value=0)
  elem0: bits[8] = array_index(s_read, indices=[idx0])
  next_arr: bits[8][2] = array(elem0, literal(value=2, bits=8))
  next_value(param=s, value=next_arr)
}

After ProcStateArrayFlatteningPass:

// After
proc my_proc(s: (bits[8], bits[8]), init={(0, 1)}) {
  s_read: (bits[8], bits[8]) = state_read(state_element=s)
  e0: bits[8] = tuple_index(s_read, index=0)
  e1: bits[8] = tuple_index(s_read, index=1)
  s_read_as_array: bits[8][2] = array(e0, e1)
  idx0: bits[1] = literal(value=0)
  elem0: bits[8] = array_index(s_read_as_array, indices=[idx0])
  next_arr: bits[8][2] = array(elem0, literal(value=2, bits=8))
  n0: bits[8] = array_index(next_arr, indices=[literal(value=0, bits=1)])
  n1: bits[8] = array_index(next_arr, indices=[literal(value=1, bits=1)])
  next_arr_as_tuple: (bits[8], bits[8]) = tuple(n0, n1)
  next_value(param=s, value=next_arr_as_tuple)
}

Subsequent ArraySimplificationPass, TupleSimplificationPass, and ProcStateTupleFlatteningPass passes then eliminate the intermediate array and tuple reconstructions and split s into two scalar bits[8] state elements.

Header

proc_state_bits_shatter - Proc State Bits Shattering

Pass which transforms Bits-type elements of the proc state into tuples of components. Only flattens where it can show that doing so will enable dynamic state feedback opportunities later (assuming it's followed by a ProcStateTupleFlatteningPass).

Note

What follows was generated by the Gemini LLM. Not human verified.

ProcStateBitsShatteringPass splits wide bits-typed StateElements in a Proc into tuples of narrower bits components when doing so will expose independent conditional state updates for ProcStateTupleFlatteningPass and NextValueOptimizationPass.

How It Works

  1. Analyzing next_value Nodes for Split Points: For each bits-typed StateElement, the pass inspects all of its next_value nodes:

    • Pass-through updates (IsNoOpNext) are ignored because they trivially preserve all sub-slices.
    • If any non-no-op next_value has a value operand that is not a concat node, the state element cannot be split.
    • For each concat next_value, candidate split boundaries (concat_splits, ordered from LSB to MSB) are computed from the bit widths of the concat's operands (iterated in reverse, since concat orders operands MSB-to-LSB).
    • Splitting is marked beneficial (could_benefit_from_splitting = true) if at least one operand of a concat is a priority_sel, or is a sel when options.split_next_value_selects (default kDefaultSplitNextValueSelects = 4) is set and sel->cases().size() <= *options.split_next_value_selects.
  2. Intersecting Split Points: When multiple non-no-op next_value nodes update the same state element, their candidate boundary sets are intersected (absl::c_set_intersection). If could_benefit_from_splitting is true and the intersection still defines more than one component (split_ends.size() > 1), the state element is shattered.

  3. State Element Transformation (TuplifyFlatStateElement): Using Proc::TransformStateElement, the bits[W] state element is replaced by a tuple (bits[w_0], bits[w_1], ..., bits[w_{k-1}]) ordered from LSB slice to MSB slice:

    • initial_value: Sliced into a tuple of Bits values corresponding to [0, split_ends[0]), [split_ends[0], split_ends[1]), etc.
    • Transforming StateReads: Uses of the old StateRead are replaced with concat(tuple_index(new_read, k-1), ..., tuple_index(new_read, 0)) (reversing the LSB-to-MSB tuple elements to match MSB-to-LSB concat order).
    • Transforming Next Values: Each next_value's value operand is replaced with tuple(bit_slice(old_val, 0, w_0), ...).

Example

// Before
proc my_proc(x: bits[16], init={0}) {
  x_read: bits[16] = state_read(state_element=x)
  x_lo: bits[6] = bit_slice(x_read, start=0, width=6)
  x_mid: bits[1] = bit_slice(x_read, start=6, width=1)
  x_hi: bits[9] = bit_slice(x_read, start=7, width=9)
  cond: bits[1] = or_reduce(x_lo)
  new_mid: bits[1] = priority_sel(cond, cases=[not(x_mid)], default=x_mid)
  next_x: bits[16] = concat(x_hi, new_mid, x_lo)
  next_value(param=x, value=next_x)
}

After ProcStateBitsShatteringPass:

// After
proc my_proc(x: (bits[6], bits[1], bits[9]), init={(0, 0, 0)}) {
  x_read: (bits[6], bits[1], bits[9]) = state_read(state_element=x)
  t_lo: bits[6] = tuple_index(x_read, index=0)
  t_mid: bits[1] = tuple_index(x_read, index=1)
  t_hi: bits[9] = tuple_index(x_read, index=2)
  x_reconstructed: bits[16] = concat(t_hi, t_mid, t_lo)
  // ... next_x computed from x_reconstructed ...
  s_lo: bits[6] = bit_slice(next_x, start=0, width=6)
  s_mid: bits[1] = bit_slice(next_x, start=6, width=1)
  s_hi: bits[9] = bit_slice(next_x, start=7, width=9)
  next_tuple: (bits[6], bits[1], bits[9]) = tuple(s_lo, s_mid, s_hi)
  next_value(param=x, value=next_tuple)
}

Followed by ProcStateTupleFlatteningPass, BitSliceSimplificationPass, and NextValueOptimizationPass, the three components become independent state elements where only the 1-bit middle element is conditionally updated.

Header

proc_state_elimination - Proc State Elimination

Pass which tries to minimize the size and total number of elements of the proc state by removal of dead state elements and zero-width elements.

Note

What follows was generated by the Gemini LLM. Not human verified.

ProcStateEliminationPass minimizes the size and total number of state elements in a Proc by removing zero-width, constant, and unobservable state elements. Fewer state elements directly reduce register count and area in synthesized hardware.

How It Works

The pass performs three elimination stages in order:

  1. Removal of Zero-Width State Elements (RemoveZeroWidthStateElements): Any state element whose flat bit count is 0 and whose type contains no tokens (!TypeHasToken) cannot store information and is removed. Its StateRead nodes are replaced with literals of its initial_value, and its Next nodes are replaced with empty tuple literals () and deleted.

  2. Removal of Constant State Elements (RemoveConstantStateElements): Using a UnionQueryEngine combining StatelessQueryEngine and a shared LazyTernaryQueryEngine, the pass checks whether each state element ever changes from its initial_value. If every Next node for a state element either passes through one of the state element's own StateReads or assigns a value proven equal to initial_value (KnownValue), the state element is constant: all of its StateReads are replaced with Literal(initial_value), and its Next nodes and state element are removed. This step runs in a fixed-point loop to collapse chains of state elements whose updates become constant once upstream state elements are replaced with literals.

  3. Removal of Unobservable State Elements (RemoveUnobservableStateElements): Identifies and removes state elements that cannot affect any observable output of the Proc:

    • Single-Cycle State Dependency Analysis: StateDependencyVisitor (a DataflowVisitor<InlineBitmap>) computes which state elements each node depends on within a single activation (unioning both data and control sources across LeafTypeTree elements).
    • State-to-State Adjacency Matrix: For each state element, the pass unions the state dependencies of the value and predicate operands of all of its Next nodes.
    • Transitive Observability (ReachableFrom): Starting from the state dependencies of all side-effecting or invoke nodes in the Proc (excluding state_read, next_value, and gate), the pass computes the transitive closure over the state-dependency graph.
    • Elimination: Any state element not reachable from a side-effecting or invoke node is unobservable. Its Next nodes are removed, any live StateReads are replaced with zero-valued literals (ZeroOfType), and the state element is removed.

Example

// Before
chan out(bits[32], id=0, kind=streaming, ops=send_only,
         flow_control=ready_valid)

top proc my_proc() {
  state_element(const_s, bits[32], init=1)
  state_element(live_s, bits[32], init=0)
  state_element(dead_s, bits[32], init=0)
  c_read: bits[32] = state_read(state_element=const_s)
  l_read: bits[32] = state_read(state_element=live_s)
  d_read: bits[32] = state_read(state_element=dead_s)
  one: bits[32] = literal(value=1)
  next_value(param=const_s, value=one)
  next_value(param=live_s, value=add(l_read, c_read))
  next_value(param=dead_s, value=add(d_read, l_read))
  tkn: token = literal(value=token)
  send.1: token = send(tkn, l_read, channel=out)
}

After ProcStateEliminationPass: * const_s is replaced by literal(value=1, bits=32) because its only update writes 1 (matching init=1). * dead_s is removed because it only feeds its own next_value and never influences send.1 or live_s.

// After (simplified)
top proc my_proc() {
  state_element(live_s, bits[32], init=0)
  l_read: bits[32] = state_read(state_element=live_s)
  c_lit: bits[32] = literal(value=1)
  next_value(param=live_s, value=add(l_read, c_lit))
  tkn: token = literal(value=token)
  send.1: token = send(tkn, l_read, channel=out)
}

Header

proc_state_fsm - Proc State Finite state machine Optimization

Pass which tries to minimize the size and total number of elements of the proc state by optimizing implicit state-machines in the state elements.

Note

What follows was generated by the Gemini LLM. Not human verified.

ProcStateFSMPass compresses state elements whose values evolve through a known finite sequence of constants into a compact binary-encoded saturating counter (state machine).

How It Works

  1. Query Engine Setup: Combines StatelessQueryEngine and a shared LazyTernaryQueryEngine via UnionQueryEngine to identify next_value expressions that evaluate to known constants (IsFullyKnown).

  2. Detecting Constant Chains (ConvertConstantChainsToStateMachines): In general, ConstantChainToStateMachine is designed to compress a shift chain of k state elements c[0..k-1] where next[c[0]] is an unconditional constant and next[c[i+1]] == state_read[c[i]] into a single binary counter of width CeilOfLog2(k) + 1 bits (avoiding a k-bit one-hot encoding). Currently, ConvertConstantChainsToStateMachines detects chains of length k = 1: any state element (of arbitrary width or compound type) that has a single unconditional next_value (predicate == std::nullopt) whose value is fully known by the query engine.

  3. State Machine Replacement (ConstantChainToStateMachine):

    • Appends a new state element state_machine_<names> of type bits[CeilOfLog2(k) + 1] initialized to 0 (marked non_synthesizable if any element in the chain was non-synthesizable).
    • Updates the state machine each tick using a saturating increment: sel(ugt(state, k - 1), cases=[add(state, 1), state]).
    • Replaces each original StateRead at chain index j with a sel indexed by state_machine whose cases are the reversed initial values [init[j], ..., init[0]] and whose default is the known constant chain_literal. For k = 1, this selects init[0] on tick 0 (when state_machine == 0) and chain_literal on all subsequent ticks (when state_machine == 1).
    • Removes the original state elements and their Next nodes, and repopulates the query engine.

Example

Suppose a 32-bit state element s starts at 0x1234_5678 on the first activation and unconditionally transitions to 0xDEAD_BEEF thereafter:

// Before
proc my_proc(s: bits[32], init={0x1234_5678}) {
  s_read: bits[32] = state_read(state_element=s)
  c: bits[32] = literal(value=0xdead_beef)
  next_value(param=s, value=c)
}

ProcStateFSMPass replaces the 32-bit register s with a 1-bit saturating counter state_machine_s:

// After
proc my_proc(state_machine_s: bits[1], init={0}) {
  state_machine_s_read: bits[1] = state_read(state_element=state_machine_s)
  one: bits[1] = literal(value=1)
  max: bits[1] = literal(value=0)
  plus_one: bits[1] = add(state_machine_s_read, one)
  too_large: bits[1] = ugt(state_machine_s_read, max)
  next_sm: bits[1] = sel(too_large, cases=[plus_one, state_machine_s_read])
  next_value(param=state_machine_s, value=next_sm)

  init_lit: bits[32] = literal(value=0x1234_5678)
  chain_lit: bits[32] = literal(value=0xdead_beef)
  s_read: bits[32] = sel(state_machine_s_read, cases=[init_lit],
                         default=chain_lit)
}

Header

proc_state_narrow - Proc State Narrowing

Pass which tries to minimize the size of the proc state by narrowing state elements using range analysis.

Note

What follows was generated by the Gemini LLM. Not human verified.

ProcStateNarrowingPass reduces the bit width of bits-typed StateElements in a Proc by analyzing how state values evolve across ticks using ProcStateRangeQueryEngine. Narrowing state elements directly reduces the number of flip-flops required in synthesized hardware.

How It Works

The pass populates a ProcStateRangeQueryEngine on the Proc (which tracks both per-bit ternary knowledge and value intervals across proc back-edges) and inspects each bits-typed StateElement:

  1. Removing Known Leading Bits (RemoveLeadingBits / ProcStateConcatNarrowTransform):

    • Computes the intersection (ternary_ops::Intersection) of the ternary vectors across all StateRead nodes for the state element.
    • Counts the number of leading (most significant) bits whose values are known constants (CountLeadingOnes on ToKnownBits). Note that these known leading bits can be any fixed bit pattern (zeros, ones, or a mix).
    • If known_leading > 0, the state element is narrowed by slicing off the top known_leading bits from its initial_value and from each next_value (bit_slice(next_val, start=0, width=new_width)). Each StateRead is reconstructed to the original width via concat(literal(leading_bits), new_state_read).

    Example (removing known leading bits):

    // Before
    proc my_proc(foo: bits[32], init={0}) {
      foo_read: bits[32] = state_read(state_element=foo)
      low_3: bits[3] = bit_slice(foo_read, start=0, width=3)
      inc: bits[3] = add(low_3, literal(value=1, bits=3))
      next_foo: bits[32] = zero_ext(inc, new_bit_count=32)
      next_value(param=foo, value=next_foo)
    }
    
    // After
    proc my_proc(foo: bits[3], init={0}) {
      foo_read: bits[3] = state_read(state_element=foo)
      leading_bits_foo: bits[29] = literal(value=0)
      extended_foo: bits[32] = concat(leading_bits_foo, foo_read)
      low_3: bits[3] = bit_slice(extended_foo, start=0, width=3)
      inc: bits[3] = add(low_3, literal(value=1, bits=3))
      next_foo: bits[32] = zero_ext(inc, new_bit_count=32)
      unexpand: bits[3] = bit_slice(next_foo, start=0, width=3)
      next_value(param=foo, value=unexpand)
    }
    
  2. Signed Range Narrowing (RemoveSignBits / ProcStateSignExtendNarrowTransform):

    • If no leading bits are constant (known_leading == 0), the pass queries qe.GetIntervals(state_read) for each StateRead of the state element and computes interval_ops::MinimumSignedBitCount (taking the maximum required signed width max_signed_bits across all reads).
    • If max_signed_bits is smaller than the state element's bit width, the state element is narrowed to max_signed_bits bits: its initial_value and next_value operands are truncated with bit_slice(..., start=0, width=max_signed_bits), and each StateRead is reconstructed to the original width via sign_ext(new_state_read, new_bit_count=old_width).

    Example (signed range narrowing for a state element bounded in [-8, 7]):

    // Before
    proc my_proc(bar: bits[32], init={0}) {
      bar_read: bits[32] = state_read(state_element=bar)
      // ... next_bar proven by ProcStateRangeQueryEngine to stay in [-8, 7]
      next_value(param=bar, value=next_bar)
    }
    
    // After
    proc my_proc(bar: bits[4], init={0}) {
      bar_read: bits[4] = state_read(state_element=bar)
      extended_bar: bits[32] = sign_ext(bar_read, new_bit_count=32)
      // ... next_bar computed using extended_bar ...
      unexpand: bits[4] = bit_slice(next_bar, start=0, width=4)
      next_value(param=bar, value=unexpand)
    }
    

Header

proc_state_provenance_narrow - Proc State Provenance Narrowing

Pass which tries to minimize the size and total number of elements of the proc state. This pass works by examining the provenance of the bits making up the next value to determine which (if any) bits are never actually modified.

NB This is a separate pass from ProcStateNarrowing for simplicity of implementation. That pass mostly assumes we'll have a range-analysis which this does not need.

Note

What follows was generated by the Gemini LLM. Not human verified.

ProcStateProvenanceNarrowingPass reduces the bit width of bits-typed StateElements in a Proc by identifying individual bit positions (leading, internal, or trailing) that never change from their initial_value across any next_value update. Unlike ProcStateNarrowingPass, which uses inter-cycle range analysis to strip leading bits, this pass uses single-cycle bit provenance and ternary analysis to excise unchanging bit segments at any offset within the bit vector.

How It Works

  1. Identifying Unchanged Bits (UnchangedBits): For each bits-typed StateElement with initial value initial_bits, the pass starts with an all-ones mask unchanged_bits and intersects it across every non-no-op Next node (!IsNoOpNext(next)):

    • Ternary Match (LazyTernaryQueryEngine): Computes ternary_known_unchanged, marking bits in next->value() that are known constants equal to the corresponding bits in initial_bits.
    • Provenance Match (BitProvenanceAnalysis): Queries provenance.GetBitSources(next->value()) (TreeBitSources) and marks any bit range whose source is a StateRead of the same state_element at the exact same bit positions (source_bit_index_low == dest_bit_index_low and source_bit_index_high == dest_bit_index_high).
    • A bit remains set in unchanged_bits if, for every Next node, it is preserved via either provenance or ternary equivalence.
  2. Extracting Bit Segments (ExtractBitSegments): If unchanged_bits is non-zero, the state element's bit range is partitioned into contiguous BitSegments ordered from MSB to LSB. Each segment is either a constant segment (holding the corresponding slice of initial_bits) or a variable segment (value == std::nullopt).

  3. State Element Transformation (NarrowTransform): Using Proc::TransformStateElement, the state element is narrowed to the concatenation of its variable segments (NarrowValue):

    • Transforming StateReads: Reconstructs the original width by concatenating (from MSB to LSB) Literal nodes for constant segments and BitSlice nodes (or new_state_read directly if there is only a single variable segment) for variable segments.
    • Transforming Next Values: Slices only the variable segments from old_next->value() (BitSlice) and concatenates them to form the narrowed next_value.

Example

Consider a 96-bit state element foo whose middle 32 bits ([32:64]) are initialized to 0xFFFF_0000 and are always either copied from foo or overwritten with 0xFFFF_0000:

// Before
proc my_proc(foo: bits[96], init={0x0000_0000_ffff_0000_0000_0000}) {
  foo_read: bits[96] = state_read(state_element=foo)
  lo: bits[32] = add(bit_slice(foo_read, start=0, width=32),
                     literal(value=1, bits=32))
  mid: bits[32] = bit_slice(foo_read, start=32, width=32)
  hi: bits[32] = add(bit_slice(foo_read, start=64, width=32),
                     literal(value=2, bits=32))
  next_foo: bits[96] = concat(hi, mid, lo)
  next_value(param=foo, value=next_foo)
}

ProcStateProvenanceNarrowingPass removes the unchanging middle 32 bits, narrowing foo from 96 bits to 64 bits:

// After
proc my_proc(foo: bits[64], init={0x0000_0000_0000_0000}) {
  foo_read: bits[64] = state_read(state_element=foo)
  var_hi: bits[32] = bit_slice(foo_read, start=32, width=32)
  const_mid: bits[32] = literal(value=0xffff_0000)
  var_lo: bits[32] = bit_slice(foo_read, start=0, width=32)
  foo_reconstructed: bits[96] = concat(var_hi, const_mid, var_lo)
  // ... next_foo computed from foo_reconstructed ...
  next_hi: bits[32] = bit_slice(next_foo, start=64, width=32)
  next_lo: bits[32] = bit_slice(next_foo, start=0, width=32)
  next_foo_slice_reduced: bits[64] = concat(next_hi, next_lo)
  next_value(param=foo, value=next_foo_slice_reduced)
}

Header

proc_state_tuple_flat - Proc State Tuple Flattening

Pass which flattens tuple elements of the proc state into their constituent components. Array elements are flattened in a different pass. Flattening improves optimizability because each state element can be considered and transformed in isolation. Flattening also gives the scheduler more flexibility; without flattening, each element in the aggregate must have the same lifetime.

Note

What follows was generated by the Gemini LLM. Not human verified.

ProcStateTupleFlatteningPass recursively decomposes tuple-typed StateElements in a Proc into separate leaf (non-tuple) StateElements. (Array-typed state elements are not decomposed by this pass; small arrays are first converted into tuples by ProcStateArrayFlatteningPass.)

How It Works

If a Proc has at least one tuple-typed StateElement (HasTupleStateElement), FlattenState rebuilds the proc state:

  1. Decomposing Initial Values (DecomposeValue): Each state element's initial_value is recursively flattened across nested tuples into a list of num_components leaf Values.

    • If num_components == 1 (e.g., a scalar state element or a 1-element tuple), the new state element retains the original name.
    • If num_components > 1, each leaf state element is named <name>_0, <name>_1, etc.
    • If num_components == 0 (an empty tuple ()), the state element decomposes into zero components and is eliminated.
  2. Decomposing StateReads (ComposeNode): For each StateRead of an original state element, a StateRead (preserving predicate and label) is created on each corresponding leaf state element. The original tuple structure is reconstructed from the leaf StateReads using Tuple nodes and replaces all uses of the original StateRead.

  3. Decomposing Next Values (DecomposeNode): For each Next node of an original state element, next->value() is recursively decomposed into leaf nodes by inserting TupleIndex operations. A separate Next node (preserving predicate and label) is created for each leaf state element.

  4. Replacing Proc State (ReplaceProcState): All old Next nodes and state elements are removed and replaced with the flattened leaf StateElements, StateReads, and Next nodes.

Example

// Before
proc my_proc(s: (bits[8], (bits[16], bits[32])), init={(1, (2, 3))}) {
  s_read: (bits[8], (bits[16], bits[32])) = state_read(state_element=s)
  a: bits[8] = tuple_index(s_read, index=0)
  inner: (bits[16], bits[32]) = tuple_index(s_read, index=1)
  next_s: (bits[8], (bits[16], bits[32])) = tuple(a, inner)
  next_value(param=s, value=next_s)
}

After ProcStateTupleFlatteningPass:

// After
proc my_proc(s_0: bits[8], s_1: bits[16], s_2: bits[32], init={1, 2, 3}) {
  s_0_read: bits[8] = state_read(state_element=s_0)
  s_1_read: bits[16] = state_read(state_element=s_1)
  s_2_read: bits[32] = state_read(state_element=s_2)
  reconstructed_inner: (bits[16], bits[32]) = tuple(s_1_read, s_2_read)
  s_read: (bits[8], (bits[16], bits[32])) = tuple(s_0_read,
                                                  reconstructed_inner)
  a: bits[8] = tuple_index(s_read, index=0)
  inner: (bits[16], bits[32]) = tuple_index(s_read, index=1)
  next_s: (bits[8], (bits[16], bits[32])) = tuple(a, inner)
  next_0: bits[8] = tuple_index(next_s, index=0)
  next_inner: (bits[16], bits[32]) = tuple_index(next_s, index=1)
  next_1: bits[16] = tuple_index(next_inner, index=0)
  next_2: bits[32] = tuple_index(next_inner, index=1)
  next_value(param=s_0, value=next_0)
  next_value(param=s_1, value=next_1)
  next_value(param=s_2, value=next_2)
}

Subsequent TupleSimplificationPass and DeadCodeEliminationPass runs simplify away the intermediate tuple and tuple_index nodes.

Header

ram_rewrite - RAM Rewrite

Pass that rewrites RAMs of one type to a new type. Generally this will be some kind of lowering from more abstract to concrete RAMs.

Note

What follows was generated by the Gemini LLM. Not human verified.

The RamRewritePass facilitates the transformation of RAM (Random Access Memory) interfaces within an XLS package. Its primary role is to lower abstract RAM models into concrete RAM representations that are directly implementable by target hardware.

The pass is driven by the ram_rewrites list in OptimizationPassOptions. Each RamRewrite entry specifies the source RAM configuration (from_config), the target RAM configuration (to_config), a mapping from logical channel names (e.g., abstract_read_req) to physical channel names in the IR (from_channels_logical_to_physical), a to_name_prefix for newly created channels, and an optional proc_name when channels are proc-scoped.

Key aspects of RamRewritePass include:

  1. RAM Abstraction Levels (RamKind): * kAbstract: A high-level, generic RAM model with separate logical channels for read requests (abstract_read_req: (addr, mask)), read responses (abstract_read_resp: (data)), write requests (abstract_write_req: (addr, data, mask)), and write completion (write_completion: ()). * k1RW (One Read/Write Port): A concrete single-port RAM that can perform either a read or a write per cycle. It uses a unified request channel (1rw_req: (addr, data, write_mask, read_mask, we, re)), a response channel (1rw_resp: (data)), and a write_completion channel (()). * k1R1W (One Read, One Write Port): A concrete RAM with independent read and write ports (1r1w_read_req: (addr, mask), 1r1w_read_resp: (data), 1r1w_write_req: (addr, data, mask), and write_completion: ()). * If a RAM configuration has no mask width defined, GetMaskType represents the absent mask as an empty tuple (), which is later stripped during codegen.

  2. Channel Mapping and Payload Repacking: For each RamRewrite, the pass inspects the existing channels to infer the common data_type and ChannelStrictness, creates the new streaming channels for to_config (configured with FlowControl::kReadyValid and zero-depth bypass FifoConfig), and rewrites all send and receive nodes referencing the old channels:

    * kAbstract to k1RW: * abstract_read_req sends of (addr, read_mask) are mapped to 1rw_req sends with repacked payload (addr, 0, 0, read_mask, we=0, re=1). * abstract_write_req sends of (addr, data, write_mask) are mapped to 1rw_req sends with repacked payload (addr, data, write_mask, 0, we=1, re=0). * abstract_read_resp receives are mapped to 1rw_resp receives, and write_completion receives are mapped to the new write_completion channel. * kAbstract to k1R1W: * abstract_read_req, abstract_read_resp, abstract_write_req, and write_completion map directly to 1r1w_read_req, 1r1w_read_resp, 1r1w_write_req, and write_completion without altering tuple layouts.

    // Original abstract read request send:
    req: (bits[10], bits[4]) = tuple(addr, mask)
    tok1: token = send(tok0, req, channel=ram_read_req)
    
    // Rewritten 1RW request send (after tuple simplification):
    zero_data: bits[32] = literal(value=0)
    zero_wmask: bits[4] = literal(value=0)
    we: bits[1] = literal(value=0)
    re: bits[1] = literal(value=1)
    rw_req: (bits[10], bits[32], bits[4], bits[4], bits[1], bits[1]) =
        tuple(addr, zero_data, zero_wmask, mask, we, re)
    tok1: token = send(tok0, rw_req, channel=ram_req)
    
  3. Channel Cleanup and Scoping: After replacing all send and receive operations in topological order, the pass removes the old channels from the package (or removes the old ChannelInterfaces from the target Proc when proc_name is set and channels are proc-scoped).

Header

reassociation - Reassociation

Reassociates associative operations to reduce delay by transforming chains of operations to a balanced tree of operations, and gathering together constants in the expression for folding.

Note

What follows was generated by the Gemini LLM. Not human verified.

The ReassociationPass is an optimization pass in XLS that reorders associative operations such as addition (add), subtraction (sub), and signed/unsigned multiplication (smul, umul). Its primary objectives are to reduce the critical path delay of the synthesized hardware and to facilitate further constant folding by grouping literal operands.

This pass is crucial for transforming deep, unbalanced chains of operations (e.g., (((A + B) + C) + D)) into more balanced tree structures (e.g., ((A + B) + (C + D))). It also effectively gathers together constant operands within an associative expression, making them amenable to subsequent constant folding optimizations.

Key Concepts:

  • Associativity: The pass exploits the associative property of operations like addition and multiplication. This property states that for an associative operation op, (A op B) op C is mathematically equivalent to A op (B op C). Reassociation leverages this to restructure the computation graph.
  • Critical Path Delay Reduction: A deep, unbalanced chain of operations in the IR directly translates to a long critical path in the hardware, which limits the maximum clock frequency. By rebalancing these chains into a shallower tree, the pass effectively reduces the overall critical path delay.
  • Constant Folding Facilitation: Grouping constant operands together within an associative expression allows the ConstantFoldingPass to combine them into a single literal. This simplifies the expression and reduces dynamic computation.
  • Overflow Handling: The pass is designed to carefully consider potential overflow conditions, particularly for signed arithmetic and operations involving different bit widths. This ensures that the semantic correctness of the original computation is rigorously preserved during reassociation.

How it Works:

  1. AssociativeElements Class: This internal helper class is central to the pass's operation. For each node identified as part of an associative chain, it recursively collects and models: * variables_: Non-constant leaf nodes (e.g., parameters or results of other complex expressions). * constants_: Constant leaf nodes (i.e., literal operations). * op_: The primary associative operation (Op::kAdd, Op::kSMul, etc.) governing the combination of these elements. * needs_negate: A boolean flag indicating if a variable needs to be logically negated, typically arising from subtraction operations (e.g., A - B is conceptually treated as A + (-B)). * overflows_: A flag indicating whether the sub-expression represented by this AssociativeElements object can potentially overflow at its current bit-width. This information is crucial for safe combination. * depth_: Tracks the depth of the longest chain of associative operations leading to this particular node.

  2. OneShotReassociationVisitor: This visitor traverses the IR in a single pass to compute and collect the AssociativeElements for each relevant node. It includes logic to handle various operations: * Associative Operations (Add, Sub, SMul, UMul): For these operations, it recursively combines the AssociativeElements of its operands, managing negation for subtraction and tracking potential overflow conditions. * Neg: Handles negation by logically flipping the needs_negate flag of its operand's AssociativeElements representation. * Extensions (ZeroExtend, SignExtend) and Concat operations that effectively act as ZeroExtend: These operations can widen a value without fundamentally changing its underlying numerical value. The pass attempts to "see through" these by propagating the AssociativeElements of the inner operand if no overflow occurs and signedness compatibility is maintained.

  3. ReassociationCache: This caching mechanism stores the computed AssociativeElements for each node. This avoids redundant computations during iterative passes and helps ensure that analyses are kept up-to-date even after transformations have altered the graph structure.

  4. Reassociate Function (Main Loop): * Fixed-Point Iteration: The pass operates in a fixed-point manner. It identifies nodes that are prime candidates for reassociation and repeatedly applies the transformation until no further beneficial changes can be made across the entire function. * Candidate Selection: Nodes are selected for reassociation if they meet specific criteria, including: * Not already a leaf node (i.e., they are part of a larger associative chain). * Not composed entirely of constants (these are handled by the separate ConstantFoldingPass). * Having users that require materialization (i.e., the reassociation is not trivially hidden by other optimizations). * Their current depth in the IR graph is greater than the minimum possible depth for a balanced tree of its elements, or they contain multiple constants that can be meaningfully grouped. * ReassociateOneOperation: This function is responsible for actually reconstructing the selected associative operation into a balanced tree: * Grouping Constants: It first groups all constant operands together to be combined by ConstantFoldingPass. * Balancing Tree: It then constructs a balanced binary tree using the variable elements, minimizing the depth of the overall computation. The tree is typically biased to the left to ensure a consistent output structure, which can further aid subsequent Common Subexpression Elimination (CSE). * Negation and Extension Handling: It correctly applies necessary negations and extensions (sign-extend/zero-extend) during the reconstruction process to strictly preserve semantic equivalence.

Benefits:

  • Reduced Critical Path: By transforming deep chains of operations into balanced trees, the pass significantly reduces the critical path delay in the generated hardware, allowing for higher clock frequencies.
  • Improved Constant Folding: Grouping constant operands together within associative expressions enables ConstantFoldingPass to reduce them to single literals, thereby simplifying the IR and reducing dynamic computation.
  • Enhanced IR Structure: Creates a more canonical and optimized structure for associative expressions, which can benefit subsequent optimization passes by providing a clearer and more efficient representation of the computation.

Example (Rebalancing additions): Consider a deep, left-leaning chain of addition operations:

// Original IR snippet (deep left-leaning chain)
fn deep_add(a: bits[32], b: bits[32], c: bits[32], d: bits[32]) -> bits[32] {
  add.1: bits[32] = add(a, b)
  add.2: bits[32] = add(add.1, c)
  ret add.3: bits[32] = add(add.2, d)
}

The ReassociationPass would transform this into a balanced tree structure:

// Optimized IR (after ReassociationPass and a subsequent DCE pass)
fn deep_add(a: bits[32], b: bits[32], c: bits[32], d: bits[32]) -> bits[32] {
  add.left: bits[32] = add(a, b)
  add.right: bits[32] = add(c, d)
  ret add.final: bits[32] = add(add.left, add.right)
}

This transformation reduces the maximum depth of the additions from 3 to 2, directly improving potential timing performance.

Header

recv_default - Receive default value simplification

Optimization which removes useless selects between the data value of a conditional or non-blocking receive and the default value of the receive (all zeros).

Note

What follows was generated by the Gemini LLM. Not human verified.

The ReceiveDefaultValueSimplificationPass is a proc-level optimization pass (OptimizationProcPass) that identifies and eliminates redundant binary select and priority_select operations choosing between the data output of a conditional or non-blocking receive and an all-zeros value.

In XLS, when a conditional receive has a false predicate, or when a non-blocking receive has no data available (its valid bit is 0), its data output (tuple_index(receive_node, index=1)) is already defined to be all zeros. Frontends or earlier passes often emit an explicit select or priority_select that forces the value to zero under those same conditions.

How it Works:

Using StatelessQueryEngine, the pass walks the proc in topological order and inspects each two-way Select (cases=[on_false, on_true], no default) and single-case PrioritySelect (cases=[on_true], default=on_false). It matches MatchUselessSelectAfterReceive when:

  1. on_true is tuple_index(receive, index=1) (the data payload of a Receive node).
  2. on_false is known to be all zeros (KnownValue(on_false)->IsAllZeros()).
  3. One of the following selector conditions holds: * Conditional receive: receive is predicated and its predicate is selector. * Non-blocking receive: receive is non-blocking and selector is the valid bit (tuple_index(..., index=2)) of a non-blocking receive.

When matched, the pass replaces the select or priority_select directly with on_true (tuple_index(receive, index=1)).

Example (Conditional receive with redundant select):

// Original IR snippet
chan in(bits[32], kind=streaming, ops=receive_only, flow_control=ready_valid)

proc p(pred: bits[1], s: bits[32], init={1, 42}) {
  tkn: token = literal(value=token)
  // Data is already 0 if pred is 0
  receive.1: (token, bits[32]) = receive(tkn, predicate=pred, channel=in)
  receive_data: bits[32] = tuple_index(receive.1, index=1)
  zero: bits[32] = literal(value=0)
  select.2: bits[32] = sel(pred, cases=[zero, receive_data])
  next (pred, select.2)
}

// Optimized IR snippet
chan in(bits[32], kind=streaming, ops=receive_only, flow_control=ready_valid)

proc p(pred: bits[1], s: bits[32], init={1, 42}) {
  tkn: token = literal(value=token)
  receive.1: (token, bits[32]) = receive(tkn, predicate=pred, channel=in)
  receive_data: bits[32] = tuple_index(receive.1, index=1)
  next (pred, receive_data)
}

Header

repopulate_cached_proc_state_info - Recompute and repopulate the cached proc-state element information.

Fully populates the cached proc-state information in the query engines.

This repopulates the givens in PartialInfoQueryEngine and LazyTernaryQueryEngine.

Note

What follows was generated by the Gemini LLM. Not human verified.

RepopulateCachedProcStateInfoPass (repopulate_cached_proc_state_info) is an analysis-refresh pass for Procs that recomputes inductive proc-state invariants and updates the shared query engines cached in OptimizationContext. It does not directly mutate the IR (always returning false), but enables stronger downstream simplifications in passes that rely on cached state-element facts.

How it Works:

  1. Inductive State Range Analysis: The pass populates a ProcStateRangeQueryEngine (base_qe) on the target Proc. This analysis examines the initial values and next_value transitions of the proc's state elements to prove inductive value ranges and known-bit invariants on state_read nodes across all proc ticks.

  2. Updating Cached Query Engines: Using CachedStateElementQueryEngine::FromContext, the pass retrieves the shared PartialInfoQueryEngine and LazyTernaryQueryEngine instances for the Proc from OptimizationContext and invokes ComputeWithStateInfo(base_qe) on each. This injects the newly proven state-element intervals and ternary bits as "givens" into those cached engines so subsequent passes (such as SelectSimplificationPass, SelectRangeSimplificationPass, and NarrowingPass) can exploit them without rerunning ProcStateRangeQueryEngine.

Example (Enabling downstream simplification via cached state ranges):

// Proc whose state `cnt` starts at 0 and wraps within [0, 3]:
proc counter(cnt: bits[8], init={0}) {
  one: bits[8] = literal(value=1)
  inc: bits[8] = add(cnt, one)
  three: bits[8] = literal(value=3)
  wrap: bits[1] = ugt(cnt, three)
  zero: bits[8] = literal(value=0)
  next_cnt: bits[8] = sel(wrap, cases=[inc, zero])
  next (next_cnt)
}

// After RepopulateCachedProcStateInfoPass populates the cached
// PartialInfoQueryEngine and LazyTernaryQueryEngine with the invariant
// cnt in [0, 3] (upper 6 bits known 0), downstream passes can fold `wrap`
// to 0 and narrow `cnt`.

Header

resource_sharing - Resource Sharing

Note

What follows was generated by the Gemini LLM. Not human verified.

The ResourceSharingPass is a critical optimization pass in XLS that aims to reduce hardware area by sharing common computational resources (e.g., adders, multipliers) among different parts of the design. This is achieved by identifying mutually exclusive operations—operations that are guaranteed not to execute at the same time—and then transforming the IR to allow them to share the same physical hardware resource through multiplexing.

The pass is configured with a ProfitabilityGuard enum, which determines the heuristic used to select which sharing opportunities to exploit:

  • kInDegree: Prioritizes sharing based on the in-degree of nodes in a conceptual "folding graph." This heuristic favors nodes that are potential "destinations" for folding, especially those with more distinct "source" operations that can be multiplexed into them. This approach is often effective for asymmetric folding scenarios where one complex operation can subsume several simpler ones.
  • kCliques: Selects sharing opportunities based on identifying cliques (groups of mutually exclusive operations) in the folding graph. This approach is particularly suitable for symmetric folding scenarios where multiple operations of similar complexity can all share a single resource.
  • kRandom: Randomly selects a subset of potential folding actions. This is typically used for testing, fuzzing, or exploration purposes rather than for deterministic optimization.
  • kAlways: Attempts to perform all possible resource sharing that is identified as legal. This is generally used for aggressive optimization benchmarking or during specific testing phases.

The core mechanism of ResourceSharingPass involves several stages:

  1. Mutual Exclusion Analysis: * ComputeMutualExclusionAnalysis: This is a central function that identifies pairs or groups of operations that are mutually exclusive. It builds a "mutual exclusivity relation" between nodes, proving that two operations are guaranteed not to be active simultaneously. * It leverages NodeForwardDependencyAnalysis to trace dataflow dependencies and BddQueryEngine (Binary Decision Diagrams) for precise logical analysis. The BddQueryEngine is critical for proving that a particular operation's value does not influence another under specific conditions (e.g., when a particular arm of a select operation is chosen). * The analysis primarily focuses on PrioritySelect operations, as these explicitly define conditional execution paths, which naturally create clear mutual exclusivity between their cases. The analysis is conservative and avoids making assumptions through Invoke nodes before function inlining to ensure correctness.

  2. Folding Graph Construction: Based on the results of the mutual exclusivity analysis, a FoldingGraph is constructed. This graph represents potential "folding actions," where a "source" operation can be "folded" into a "destination" operation, implying that they can share the same underlying hardware resource. This sharing is controlled by a select operation whose condition is derived from the mutual exclusivity proof.

  3. Profitability Estimation: * The pass utilizes AreaEstimator and DelayEstimator tools to assess the profitability of each potential folding action. This involves a cost-benefit analysis. * EstimateAreaForSelectingASingleInput: Calculates the area overhead associated with adding multiplexers (select logic) required to steer the inputs to a shared resource. * EstimateAreaForNegatingNode: Estimates the area cost if an operand needs to be negated (e.g., when folding a sub operation into an add operation that operates on the negated operand). * The area_saved for a folding action is calculated as the estimated area of the "from" node minus the area overhead of the multiplexers and any additional required logic. * DelayAnalysis is used to consider the impact of sharing on the critical path delay. The kMaxDelaySpread constant defines an acceptable limit for the increase in delay due to multiplexing.

  4. Selection of Folding Actions: * SelectFoldingActions: This function, guided by the chosen ProfitabilityGuard heuristic, selects a subset of the legal and profitable folding actions to perform. * It prioritizes actions that offer significant area savings while keeping delay impacts within acceptable bounds. * The selected actions are sorted (e.g., by descending area savings) and then "legalized" (LegalizeSequenceOfFolding) to prevent overlapping or conflicting transformations from being applied.

  5. IR Transformation: Once a final set of NaryFoldingActions is selected, the IR is transformed to implement the sharing. This involves: * Creating new select or priority_select operations (or chains of them) to multiplex the inputs of the shared resource based on the conditions derived from the original mutual exclusivity. * Replacing the original "from" operations with the output of the newly created multiplexing structure, which then feeds into the "to" (shared) operation. * Removing the now redundant "from" operations.

Example: Consider two umul operations, mul0(a, b) and mul1(c, d), which are mutually exclusive (e.g., they are in different arms of a priority_select). The ResourceSharingPass might identify this and transform the IR to use a single shared umul hardware resource:

// Original IR snippet (simplified)
selector: bits[1] = ...
mul0: bits[32] = umul(a, b, width=32)
mul1: bits[32] = umul(c, d, width=32)
ret result: bits[32] = priority_sel(selector, cases=[mul0], default=mul1)

After ResourceSharingPass (conceptual representation, as actual IR is more complex with explicit multiplexing):

// Optimized IR snippet (simplified)
selector: bits[1] = ...

// Multiplexed inputs to the shared multiplier
input_a_mux: bits[32] = priority_sel(selector, cases=[a], default=c)
input_b_mux: bits[32] = priority_sel(selector, cases=[b], default=d)

// Shared multiplier operation
umul_shared: bits[32] = umul(input_a_mux, input_b_mux, width=32)

ret result: bits[32] = umul_shared // The shared multiplier is now the result

This pass is vital for achieving high-quality hardware designs by efficiently utilizing available hardware resources, particularly in designs with significant conditional logic.

Header

scheduling-opt - scheduling opt passes

Passes performed immediately before starting scheduling.

These optimizations are used to fix up any changes the mutual-exclusion pass & proc-state legalize performs before the initial scheduling.

TODO(allight): We might wish to move these into opt only. sched running optimization passes is an artifact of how these tools evolved which no longer makes too much sense. To do this will require making a decision on how to handle 'mutual-exclusion opt' however.

Text-proto

Options Set

Min opt level: 1

Invoked Passes

select_lifting - Select Lifting

Pass which replace the pattern v = sel (c, array[i], array[j], ...) where all cases of the select reference the same array, to the code z = sel (c, i, j, ...) v = array[z]

Note

What follows was generated by the Gemini LLM. Not human verified.

The SelectLiftingPass is an optimization pass in XLS that restructures select and priority_select operations to improve hardware efficiency. It identifies scenarios where a select's cases are all derived from a common "shared" operation (such as an array_index or a binary arithmetic operation) and "lifts" that shared operation out of the select. This transformation effectively moves the multiplexing (the select) from the output of the shared operation to its input, which often leads to significant hardware savings and can sometimes improve performance.

This pass is particularly effective in two main scenarios:

  1. Lifting ArrayIndex Operations: When all cases of a select are array_index operations on the same array, the pass can lift the array_index out of the select. It creates a new select that chooses between the indices of the original array_index operations. The result of this new select (the chosen index) is then used in a single, shared array_index operation. This replaces multiple array reads followed by a wide data multiplexer with a smaller index multiplexer followed by a single array read, which is generally much more area-efficient.

    // Original IR snippet
    v = sel(c, array[i], array[j])
    
    // Optimized IR (after lifting)
    z = sel(c, i, j)
    v = array[z]
    
  2. Lifting Binary Operations: When all cases of a select are binary operations of the same kind (e.g., all adds, subs, or muls) and share one common operand, the binary operation can be lifted out of the select. A new select is created to choose between the "other" (non-shared) operands. The result of this new select is then used in a single, shared binary operation with the common operand.

    // Original IR snippet
    v = sel(c, x + a, x + b)
    
    // Optimized IR (after lifting)
    z = sel(c, a, b)
    v = x + z
    

Profitability and Applicability Guards:

The pass includes several "guards" to ensure that the transformation is both applicable and profitable:

  • CanLiftSelect: This function checks if a select is a candidate for lifting. For ArrayIndex lifting, it verifies that all cases are indeed array_index operations on the same array and that their index types are compatible. For binary operation lifting, it identifies a common shared_node across all cases and ensures the operation type is consistent and supported (e.g., add, sub, and, or, mul, shifts). It also handles "identity" cases, where one of the select's cases is the shared operand itself.
  • ShouldLiftSelect: This function determines if a liftable select should actually be transformed, based on profitability heuristics: * Area Estimation: For binary operations, it performs a simple cost-benefit analysis based on the bit-widths of the original and transformed operations. The transformation is generally considered profitable if the total bit-width of the new, narrower select and the shared operation is less than or equal to the total bit-width of the original select and all the individual binary operations (if they were single-use). * Delay Estimation: If a delay_model is provided, the pass uses CriticalPathDelayAnalysis to estimate the impact of the transformation on the critical path. Lifting is avoided if it is predicted to increase the latency. This is particularly important for scenarios like converting multiple constant-shifts into a single variable-shift, which is often more expensive in hardware. * Heuristics for High-Latency Operations: For high-latency operations like multiplication, lifting is more cautiously applied, especially if it involves identity cases, to avoid potentially degrading performance.

How it Works:

  1. Worklist-based Iteration: The pass maintains a worklist of select and priority_select nodes that are candidates for optimization. It iterates through this worklist, applying transformations until no more profitable lifting opportunities can be found.

  2. Applicability and Profitability Checks: For each select in the worklist, it calls CanLiftSelect and then ShouldLiftSelect to determine if a valid and beneficial transformation exists.

  3. IR Transformation: If a transformation is approved: * LiftSelectForArrayIndex: Rewires the IR for array_index lifting by creating a new select for the indices and a new shared array_index. * LiftSelectForBinaryOperation: Rewires the IR for binary operation lifting by creating a new select for the non-shared operands and a new shared binary operation. It correctly handles identity cases by inserting the appropriate identity literal (e.g., 0 for add, -1 for and) into the new select.

  4. Cleanup: The original select node, now redundant, is marked for deletion, which is typically handled by a subsequent DeadCodeEliminationPass. Any new select nodes created during the transformation are added to the worklist, allowing for potential further optimizations.

By systematically applying these transformations, SelectLiftingPass plays a crucial role in optimizing multiplexer-heavy designs, leading to more efficient use of hardware resources and improved overall performance.

Header

select_merge - Select Merging

Note

What follows was generated by the Gemini LLM. Not human verified.

The SelectMergingPass merges consecutive OneHotSelect or PrioritySelect operations in a FunctionBase into a single, larger select operation of the same kind. Flattening cascades of single-use selects into a unified select simplifies the IR and allows downstream passes (such as select simplification) and hardware synthesis tools to optimize across all cases at once.

How it Works:

The pass traverses the IR in topological order (TopoSort) and invokes MergeSelectNode on each OneHotSelect and PrioritySelect node:

  1. Merging OneHotSelect Operations: * Pattern: An outer OneHotSelect where one or more cases are themselves single-use OneHotSelect nodes (users().size() == 1). * Transformation: Constructs a single merged OneHotSelect: * Contiguous runs of unmerged cases have their corresponding selector slice extracted via bit_slice. * For each case i that is a single-use OneHotSelect, bit i of the outer selector is extracted (bit_slice), sign-extended to the bit-width of the inner selector (sign_ext), and bitwise and-ed with the inner selector. Its cases are spliced directly into the merged case list. * All selector pieces are concatenated (from MSB to LSB) via CreateFlattenedConcat (so nested Concat trees in selector pieces are flattened immediately) to form the new selector.

  2. Merging PrioritySelect Operations: * Selector Inversion for 1-Bit PrioritySelects: If a 1-bit PrioritySelect has a single-use PrioritySelect as cases[0] and its default_value is not a single-use PrioritySelect, the pass first negates the 1-bit selector (not) and swaps cases[0] with default_value. Merging an inner PrioritySelect from the default_value position is simpler because its default value directly becomes the merged default_value without needing an explicit inner_selector == 0 fallback condition. * Case Merging: For any case i that is a single-use PrioritySelect, bit i of the outer selector is sign-extended and and-ed with the inner selector to guard the inner cases, followed by an additional case for the inner default_value guarded by and(outer_selector[i], eq(inner_selector, 0)). * Default Value Merging: If the outer default_value is a single-use PrioritySelect, its selector and cases are appended at the lowest-priority end of the merged PrioritySelect, and its default_value becomes the new outer default_value. * All selector pieces are concatenated via CreateFlattenedConcat to form the merged selector.

Key Conditions for Merging:

  • Single Use: An inner select is only merged if users().size() == 1, preventing logic duplication.
  • Matching Select Types: OneHotSelect nodes are only merged into OneHotSelect, and PrioritySelect nodes are only merged into PrioritySelect.

Example (OneHotSelect merging):

// Original IR snippet
fn f(p0: bits[2], p1: bits[2], x: bits[32], y: bits[32],
     z: bits[32]) -> bits[32] {
  one_hot_sel.1: bits[32] = one_hot_sel(p0, cases=[x, y])
  ret one_hot_sel.2: bits[32] = one_hot_sel(p1, cases=[one_hot_sel.1, z])
}

Because one_hot_sel.1 has only one user (one_hot_sel.2), SelectMergingPass merges them into a single 3-case one_hot_sel:

// Optimized IR
fn f(p0: bits[2], p1: bits[2], x: bits[32], y: bits[32],
     z: bits[32]) -> bits[32] {
  bit_slice.3: bits[1] = bit_slice(p1, start=0, width=1)
  sign_ext.4: bits[2] = sign_ext(bit_slice.3, new_bit_count=2)
  and.5: bits[2] = and(sign_ext.4, p0)
  bit_slice.6: bits[1] = bit_slice(p1, start=1, width=1)
  new_selector: bits[3] = concat(bit_slice.6, and.5)
  ret one_hot_sel.7: bits[32] = one_hot_sel(new_selector, cases=[x, y, z])
}

Header

select_range_simp - Select Range Simplification

Pass which simplifies selects and one-hot-selects. Example optimizations include removing dead arms and eliminating selects with constant selectors. Uses range analysis to determine possible values.

Note

What follows was generated by the Gemini LLM. Not human verified.

SelectRangeSimplificationPass (select_range_simp) runs the select simplification suite (SelectSimplificationPassBase) with with_range_analysis=true. Instead of LazyTernaryQueryEngine, it combines StatelessQueryEngine with PartialInfoQueryEngine (wrapped in CachedStateElementQueryEngine for Procs, plus BitProvenanceAnalysis when SplitsEnabled) to reason over combined ternary and interval/range information directly.

Enabling range analysis extends all SelectSimplificationPass optimizations with interval-aware reasoning:

  • Range-Proven Selector Constraints: PartialInfoQueryEngine can prove that selector bits are constant, mutually exclusive (AtMostOneBitTrue), exhaustive (AtLeastOneTrue / AtLeastOneBitTrue), or one-hot (ExactlyOneBitTrue) based on value intervals (such as bounded loop indices or arithmetic comparisons) that ternary analysis alone cannot resolve. This unlocks additional dead-arm pruning, PrioritySelect selector narrowing, mask conversion, and comparison hoisting.
  • Sign-Extension Width Squeezing (TrySqueezeSelect): When SplitsEnabled and with_range_analysis=true, TrySqueezeSelect queries PartialInfoQueryEngine::GetIntervals on each select arm and computes interval_ops::MinimumSignedBitCount across all cases. If all arms fit in a narrower signed bit-width W, the select is narrowed to W bits and sign-extended (sign_ext) back to the original width.

Header

select_simp - Select Simplification

Pass which simplifies selects and one-hot-selects. Example optimizations include removing dead arms and eliminating selects with constant selectors. Uses ternary analysis to determine possible values.

Note

What follows was generated by the Gemini LLM. Not human verified.

SelectSimplificationPass (select_simp) simplifies select, one_hot_select, priority_select, and one_hot operations in a FunctionBase by running SelectSimplificationPassBase with with_range_analysis=false. It uses a UnionQueryEngine combining StatelessQueryEngine and LazyTernaryQueryEngine (plus BitProvenanceAnalysis when SplitsEnabled) to evaluate known bits and bit provenance without the overhead of full interval/range analysis.

Key optimizations performed include:

  • Hoisting Comparisons with Literals: Pushes comparisons (CompareOp) against a literal through a single-use Select, PrioritySelect, or 1-hot OneHotSelect when at most one arm is non-literal.
  • Constant and Known Selector Elimination: Replaces Select, PrioritySelect, and OneHotSelect nodes when their selector bits uniquely determine the active case(s) or default value.
  • Three-Way Comparison Canonicalization: Rewrites nested 2-way Select and PrioritySelect three-way comparisons (< and >) so the second comparison uses eq.
  • Identical Arms & Selector Reordering: Folds selects with identical arms, reduces identical-arm OneHotSelects to a 1-bit Select on selector != 0, and reorders Select cases when the selector is a unary function of a narrower or equal-width base value.
  • Tuple Decomposition: Splits tuple-typed Select, OneHotSelect, and PrioritySelect nodes into per-element selects bundled in a Tuple.
  • Arm Commoning, Pruning, and Gate Lowering: Merges duplicate arms in OneHotSelect (NarrowingEnabled) and adjacent duplicate arms in PrioritySelect (SimplifyPrioritySelectDuplicateCases), absorbs inverted 1-bit selectors (not), lowers 1-bit muxes with constant/selector arms into and/or/not gates, converts single-nonzero-arm selects into and masks (SplitsEnabled), and prunes dead/zero arms.
  • Width Squeezing and Consecutive Select Collapsing: Slices off common known constant or provenance-shared leading/trailing bits across select arms (SplitsEnabled), and collapses consecutive 2-way Selects that share a common case or selector.
  • OneHot Lowering and Bit-Based Select Splitting: Converts OneHotSelect(OneHot(x)) into PrioritySelect, simplifies OneHot on 1-bit, mutually exclusive, or single-unknown-bit inputs, and splits OneHotSelect/PrioritySelect nodes (<= 64 bits) along runs of shared vs. distinct bit sources (SplitsEnabled).

Header

select_to_bitwise_ops - Select to Bitwise Ops

Converts a binary select whose two arms provably differ by a fully-known XOR term (e.g. sel(p, [x, xor(x, c)])) into an XOR with an AND-masked constant: xor(x, and(sign_ext(p, W), c)), with p complemented when the XOR arm is the on-false case. The arms need not literally form xor(base, c): per-piece xor-with-constant differences introduced by earlier passes (e.g. concat_simp) are also recognized. This is the select pattern generated by the per-step of an unrolled CRC/shift loop.

This pass is separate from select simplification (and runs at the very end of optimization) by design:

  • The rewrite is value-based: it only fires when the query engine can prove the two arms differ by a fully-known constant, unlike the rest of select simplification which reasons about the shape of the select itself.
  • It deliberately consumes shapes that concat_simp produces (wide xor limbs split into per-slice concats). concat_simp runs inside the fixed-point "simp" compound, and running this rewrite in the same fixed point would leave the two transforms repeatedly reshaping the same IR instead of converging.
  • It converts the select into an and-masked xor, which value-based analyses reason through less easily, so it is deferred until after those analyses (e.g. conditional specialization) have already run.

Runs only at optimization levels where split-based rewrites are enabled (SplitsEnabled).

Note

What follows was generated by the Gemini LLM. Not human verified.

How it Works:

  1. Eligibility (GetBinaryMuxArms): The pass only runs when options.splits_enabled() is true. It inspects each Select and PrioritySelect with a 1-bit selector (p) and flat bit-vector type (W >= 1) in topological order, extracting its (on_false, on_true) arms (cases[0] and cases[1] for Select, or default_value and cases[0] for PrioritySelect). If either arm is already known to be all zeros or all ones (IsZeroOrOnes), the select is skipped so standard select simplification handles it.

  2. Direct and Recursive XOR Delta Matching: Using a UnionQueryEngine combining StatelessQueryEngine and LazyTernaryQueryEngine, the pass attempts to prove that the two arms differ by a fully known constant delta (on_true ^ on_false == delta): * Direct Match (MatchXorCase): Checks whether one arm is a binary xor(base, c) (or xor(c, base)) where base is the other arm and c is fully known (query_engine.IsFullyKnown(c)). * Recursive Structural Match (TryFoldXorDelta): Performs a memoized, depth-bounded (kMaxXorFoldDepth = 1000) structural walk over pairs of nodes (a, b) of equal bit-width: * If a == b, the XOR delta is 0. * If both a and b are fully known constants, the delta is *KnownValue(a) ^ *KnownValue(b). * If a (or b) is a binary xor with a fully known operand c and variable operand x, recurses on (x, b) (or (a, x)) and XORs the resulting delta with c. * If a (or b) is not(x), recurses on (x, b) (or (a, x)) and bitwise-inverts the resulting delta. * If both a and b are concat trees whose flattened operands (FlattenConcats) have pairwise matching bit-widths, recurses on each operand pair and concatenates the piece deltas.

  3. Bitwise Lowering: Once a base arm and a non-zero delta (Bits) are determined (with condition cond = p if base == on_false, or cond = not(p) if base == on_true): * For 1-bit selects (W == 1), delta is 1 (on_true == not(on_false)), and the pass avoids sign_ext/and by emitting xor(on_false, p) directly (or not(xor(on_true, p)) when on_false is the not/xor node and on_true is the simpler base). * For wider selects (W > 1), the select is replaced with xor(base, sign_ext(cond, W)) when delta is all-ones, or xor(base, and(sign_ext(cond, W), literal(delta))) otherwise.

Example:

// Original IR
fn crc_step(p: bits[1], x: bits[8]) -> bits[8] {
  poly: bits[8] = literal(value=0x07)
  x_xor_poly: bits[8] = xor(x, poly)
  ret sel.1: bits[8] = sel(p, cases=[x, x_xor_poly])
}

// Optimized IR
fn crc_step(p: bits[1], x: bits[8]) -> bits[8] {
  mask: bits[8] = sign_ext(p, new_bit_count=8)
  delta: bits[8] = literal(value=0x07)
  masked_delta: bits[8] = and(mask, delta)
  ret xor.2: bits[8] = xor(x, masked_delta)
}

Header

simp - Simplification

Standard simplification pipeline.

This is run a large number of times and avoids many time-consuming analyses.

Text-proto

Invoked Passes

simp(2) - Max-2 Simplification

Standard simplification pipeline.

Opt level is capped at 2

Text-proto

Options Set

Cap opt level: 2

Invoked Passes

simp(3) - Max-3 Simplification

Standard simplification pipeline.

Opt level is capped at 3

Text-proto

Options Set

Cap opt level: 3

Invoked Passes

simp(>=1,<=2) - Min-1 Max-2 Simplification

Standard simplification pipeline.

Opt level is capped at 2 and skipped if less than 1

Text-proto

Options Set

Min opt level: 1

Cap opt level: 2

Invoked Passes

simplify-and-inline - Iteratively inline and simplify

Inlining segment of the pipeline

This is performed to fixedpoint and each run a single layer of the function hierarchy is inlined away.

Text-proto

Options Set

Run to a fixedpoint.

Invoked Passes

sparsify_select - Sparsify Select

The SparsifySelectPass is a type of range analysis-informed dead code elimination that removes cases from selects when range analysis proves that they can never occur. It does this by splitting a select into many selects, each of which covers a single interval from the selector interval set.

Note

What follows was generated by the Gemini LLM. Not human verified.

The SparsifySelectPass uses range analysis to eliminate unreachable cases from select operations. When the set of possible values that a select's selector can take covers fewer points than the number of cases in the select, this pass replaces the original select with a smaller select (or a chain of selects, one per reachable interval) that only indexes into the reachable cases.

Here is a detailed breakdown of its operation:

  1. Range Analysis: The pass populates a PartialInfoQueryEngine and queries GetIntervals(select->selector()).Get({}) to obtain the IntervalSet of possible values for the selector of each Select node.

  2. Sparsity Check: If the total number of values in the IntervalSet (selector_intervals.Size()) is strictly less than select->cases().size(), then at least one case in the select is provably unreachable.

  3. Splitting into Per-Interval Selects (SparsifySelect): * IntervalsSortedBySize sorts the convex intervals in selector_intervals from smallest to largest (breaking ties by interval order). * For each reachable Interval [lower, upper], the pass collects the corresponding slice of cases from the original select (using select->default_value() for indices >= select->cases().size(), or skipping the interval if it lies entirely past the end of cases() and no default_value is present). * It constructs an inner select for the interval: if_in_range = sel(sub(selector, lower), cases=cases_in_range, default=0). * For the first interval processed (is_leaf == true), if_in_range is used directly without a range-check comparator (if the selector falls in no other interval, it must fall in this leaf interval). * For each subsequent interval (is_leaf == false), the pass checks whether selector lies in [lower, upper] via and(uge(selector, lower), ule(selector, upper)) and wraps the previously constructed select chain (other) in a 2-way select: sel(in_bounds, cases=[other, if_in_range]).

Example: Consider a select operation where the selector add.3 is a bits[4] value proven by range analysis to lie in the single interval [8, 11]:

// Original IR snippet
fn func(x: bits[2]) -> bits[4] {
  zero_ext.1: bits[4] = zero_ext(x, new_bit_count=4)
  literal.2: bits[4] = literal(value=8)
  add.3: bits[4] = add(zero_ext.1, literal.2)
  // 16 cases (literal.4 through literal.19) for selector values 0..15:
  ret sel.20: bits[4] = sel(add.3, cases=[
    literal.4, literal.5, literal.6, literal.7, literal.8, literal.9,
    literal.10, literal.11, literal.12, literal.13, literal.14,
    literal.15, literal.16, literal.17, literal.18, literal.19
  ])
}

Because add.3 only takes values in [8, 11], SparsifySelectPass replaces the 16-way sel.20 with a 4-case select offset by the interval lower bound (8):

// Optimized IR snippet
fn func(x: bits[2]) -> bits[4] {
  zero_ext.1: bits[4] = zero_ext(x, new_bit_count=4)
  literal.2: bits[4] = literal(value=8)
  add.3: bits[4] = add(zero_ext.1, literal.2)
  lower_bound: bits[4] = literal(value=8)
  offset: bits[4] = sub(add.3, lower_bound)
  zero: bits[4] = literal(value=0)
  ret sel.21: bits[4] = sel(offset,
      cases=[literal.12, literal.13, literal.14, literal.15],
      default=zero)
}

If the selector's IntervalSet contains multiple disjoint intervals, the first (smallest) interval forms the leaf select, and each subsequent interval wraps it in sel(and(uge(selector, lower), ule(selector, upper)), cases=[previous_chain, interval_select]).

Header

strength_red - Strength Reduction

Replaces operations with equivalent cheaper operations. For example, an add with no possible carries may be replaced with a bitwise OR.

Note

What follows was generated by the Gemini LLM. Not human verified.

The StrengthReductionPass is an optimization pass in XLS that improves hardware efficiency by replacing computationally expensive operations with equivalent, cheaper primitives. This reduces the area, critical-path delay, and power consumption of the generated hardware by leveraging known constant operands and bit-level value properties.

The pass traverses the IR in topological order and queries a UnionQueryEngine combining StatelessQueryEngine and a context-cached PartialInfoQueryEngine (wrapped in CachedStateElementQueryEngine) to inspect known bits, leading/trailing zeros, and sign bits.

Key strength reductions performed by this pass include:

  1. Replacement of Fully Known Nodes with Literals (NarrowingEnabled): If the QueryEngine proves that a non-literal node with at least one user always evaluates to a constant value, it is replaced with a literal node.

  2. Sinking Operations into Selects: If a non-side-effecting, non-invoke operation has an operand that is a sel (Select) whose cases (and default, if present) are all known constants, the operation is sunk into the sel cases whenever: * All other operands of the operation are also known constants, or * The sel feeds the index, start offset, selector, or shift amount of an operation that simplifies when that operand is constant (1D array_index, array_slice, bit_slice_update, dynamic_bit_slice, sel, priority_sel, shll, shra, shrl), provided doing so does not widen the sel via a cheap widening op (array, array_concat, concat, sign_ext, tuple, zero_ext).

    // Original IR
    v1: bits[32] = sel(selector, cases=[const1, const2])
    v2: bits[32] = add(v1, const3)
    
    // Optimized IR
    v1_c1: bits[32] = add(const1, const3)
    v1_c2: bits[32] = add(const2, const3)
    v2: bits[32] = sel(selector, cases=[v1_c1, v1_c2])
    
  3. Additions (add): * Addition with Zero: add(x, 0) or add(0, x) is replaced with x. * Addition to Bitwise OR (No Carry): If at every bit position i, at least one operand is known to be 0, no carry can be generated and add(a, b) is replaced with or(a, b). * Adding a Value to Itself: add(a, a) is replaced with concat(bit_slice(a, start=0, width=W-1), 0:bits[1]), which shifts left by 1 bit with zero logic delay. * Narrowing Low Known-Zero Bits (SplitsEnabled): If either operand has k > 0 known trailing zeros, only the upper W - k bits are added and concatenated with the lower k bits of the other operand. * Splitting Adders at Non-Propagating Carries (SplitsEnabled): If both operands are known to be 0 at bit i (i < W - 1), a carry cannot propagate past bit i. The adder is split at bit i + 1 into smaller independent adders whose results are concatenated.

  4. Subtractions (sub): * Subtraction of Zero: sub(x, 0) is replaced with x. * Subtracting from All-Ones: sub(all_ones, x) is replaced with not(x). * Narrowing Low Known Bits (SplitsEnabled): If the LHS has k known trailing ones (more than the RHS's known trailing zeros), only the upper W - k bits are subtracted and concatenated with not(bit_slice(rhs, start=0, width=k)). Otherwise, if the RHS has k > 0 known trailing zeros, only the upper W - k bits are subtracted and concatenated with bit_slice(lhs, start=0, width=k). * Splitting Subtractors at Non-Propagating Borrows (SplitsEnabled): If at bit i (i < W - 1) the LHS bit is known 1 and the RHS bit is known 0, a borrow cannot propagate past bit i, so the subtractor is split at bit i + 1 into smaller independent subtractors concatenated together.

  5. Bitwise AND with a Contiguous Mask (and) (NarrowingEnabled): A binary and(x, mask) where mask is known to have a single contiguous run of set bits (e.g., 0b001110) is replaced with concat(0, bit_slice(x, start=trailing_zeros, width=selected_bits), 0).

  6. Single-Bit Select Expansion and Sign-Extension Detection: * Exploding 1-Bit Muxes (SplitsEnabled): A 1-bit sel with a 1-bit selector s where at least one branch is a literal or equals s is expanded into or(and(s, on_true), and(not(s), on_false)). * Select to SignExt: A sel with a 1-bit selector that chooses between all-zeros and all-ones is replaced with sign_ext(s) (or sign_ext(not(s)) if inverted).

  7. SignExt to ZeroExt: If the MSB of the operand of sign_ext(x) is known to be 0, the operation is replaced with zero_ext(x).

  8. Gate Simplification: * If condition is known 1, gate(cond, data) is replaced with data. * If condition is known 0 or data is known all-zeros, the gate is replaced with a zero literal.

  9. Single-Bit Add / Ne and Small Comparisons: * 1-bit add(x, y) and ne(x, y) are replaced with xor(x, y). * When NarrowingEnabled, unsigned comparisons against a power-of-two constant (uge(x, 2^k) and ult(x, 2^k)) are strength-reduced to comparing the upper W - k bits (bit_slice(x, start=k, width=W-k)) against 0 using ne or eq. * When NarrowingEnabled, a 2-bit equality check against zero (eq(x, 0b00)) is replaced with not(or(bit_slice(x, 0, 1), bit_slice(x, 1, 1))).

  10. Expensive Arithmetic with a Single Unknown Bit (NarrowingEnabled): For smul, umul, sdiv, udiv, smod, and umod where across both operands only a single bit is unknown (all other bits are known constants), the pass evaluates the operation for both possible values of that bit using InterpretNode and replaces the arithmetic op with a sel driven by an eq comparison of the operand containing the unknown bit against one of its two constant completions.

Header

table_switch - Table switch conversion

TableSwitchPass converts chains of Select/PrioritySelect nodes into ArrayIndex ops. These chains have the form: sel.(N)(eq.X, literal.A, literal.B) sel.(N+1)(eq.Y, sel.(N), literal.C) sel.(N+2)(eq.Z, sel.(N+1), literal.D) And so on. In these chains, eq.X, eq.Y, and eq.Z must all be eq or ne comparisons of the same value against constant keys.

Current limitations: - Chains must contain at least 3 links. - Keys must fit in uint64_t, and matched values (plus the final fall-through value if the index space is not fully covered) must be literals. - Matched keys must cover either the entire index space or more than half of [0, min(2^width, max_key + 2)). - Select ops must be binary, and PrioritySelect selectors must be 1-bit or a Concat of 1-bit selectors.

Note

What follows was generated by the Gemini LLM. Not human verified.

The TableSwitchPass is an optimization pass in XLS that transforms cascaded chains of sel and priority_sel nodes into direct array_index table lookups on an array literal. Replacing a chain of conditional branches comparing a common index against constant keys with a single constant-array lookup simplifies control logic and improves hardware area and delay.

How it Works:

  1. Chain Matching (MatchLinks): * The pass traverses nodes in reverse topological order (Use-before- Def, via context.ReverseTopoSort(f)) and records interior links in a transformed set so it matches outermost lookup-chain roots first and skips interior links already folded into an outer table. It uses a StatelessQueryEngine to resolve constant uint64_t keys. * Each link in the chain is either: * A binary sel or 1-bit priority_sel whose selector compares a common index node against a constant uint64_t key using eq or ne, selecting a literal value on match and forwarding to the next node on mismatch, or * A multi-case priority_sel whose selector is a concat of 1-bit eq/ne comparisons against the same index node (with ne only permitted on the final case), which contributes multiple consecutive links to the chain. If only a suffix of a priority_sel's cases starts the chain (at first_case > 0), the prefix cases are preserved in a truncated priority_sel whose default value becomes the new array_index. * Chains with 2 or fewer links (links.size() <= 2) are skipped as too short to benefit from table conversion.

  2. Table Construction (LinksToTable): * The pass walks the chain from outermost to innermost link, recording the first Literal value associated with each uint64_t key (later duplicate keys in the chain are unreachable and ignored). * Full Index Space Coverage: If the index width is < 63 bits and the matched keys cover all 2^width possible index values, the final fall-through (else) value is dead and need not be a literal; the pass emits an array literal of size 2^width. * Partial / Sparse Coverage with Saturation: Otherwise, the final fall-through node must be a Literal (else_value). Leveraging XLS array_index out-of-bounds saturation semantics (where any index >= size - 1 clamps to the last element), the pass bounds the table size to min(2^width, max_key + 2). If more than half of the entries in [0, table_size) are explicitly matched (map.size() * 2 > table_size), any missing indices (gaps) and the saturating final slot are filled with else_value.

  3. Replacement: The pass creates a literal array containing the table entries and replaces the root of the chain with array_index(array_literal, indices=[index]).

Example:

// Original IR
fn main(index: bits[32]) -> bits[32] {
  literal.0: bits[32] = literal(value=0)
  literal.1: bits[32] = literal(value=1)
  literal.2: bits[32] = literal(value=2)
  literal.10: bits[32] = literal(value=10)
  literal.20: bits[32] = literal(value=20)
  literal.30: bits[32] = literal(value=30)
  literal.99: bits[32] = literal(value=99)
  eq.4: bits[1] = eq(index, literal.0)
  eq.5: bits[1] = eq(index, literal.1)
  eq.6: bits[1] = eq(index, literal.2)
  sel.7: bits[32] = sel(eq.4, cases=[literal.99, literal.10])
  sel.8: bits[32] = sel(eq.5, cases=[sel.7, literal.20])
  ret sel.9: bits[32] = sel(eq.6, cases=[sel.8, literal.30])
}

// Optimized IR (after dead code elimination)
fn main(index: bits[32]) -> bits[32] {
  array_literal: bits[32][4] = literal(value=[10, 20, 30, 99])
  ret array_index.10: bits[32] = array_index(array_literal, indices=[index])
}

Header

token_dependency - Convert data dependencies between effectful operations into token dependencies

Pass which turns data dependencies between certain effectful operations into token dependencies. In particular, transitive data dependencies between receives and other effectful ops are turned into token dependencies whenever no such token dependency already exists.

Note

What follows was generated by the Gemini LLM. Not human verified.

The TokenDependencyPass ensures that ordering constraints implied by data dependencies between receive operations and downstream side-effecting token-consuming operations (such as send, receive, or assert) are explicitly captured in the token dependency graph.

For example, if a send operation consumes a value derived from a receive operation's payload, but subsequent algebraic optimizations prove that the expression is independent of the received value (e.g., multiplied by zero or masked off), later passes could eliminate the data dependency. Without an explicit token path from the receive to the send, the scheduler could reorder the two I/O operations and violate program semantics.

How it Works:

  1. Token Provenance & Transitive Closure: The pass runs TokenProvenanceAnalysis on the FunctionBase to build the direct token dependency graph over side-effecting operations and after_all nodes, and computes its TransitiveClosure.
  2. Data Dependency Search: For each receive operation a, the pass performs a depth-first search over the data dependency graph to find all downstream side-effecting token operations b that are not already reachable from a in the token transitive closure.
  3. Transitive Pruning: If operation c is token-dependent on operation b, and both b and c are data-dependent on receive a, the pass prunes a from c's required set (minimal_io_to_data_supplying_io), since adding a token edge from a to b transitively orders a before c.
  4. Token Rewiring: For each remaining pair (io, supplying_receive), the pass extracts the token output of supplying_receive via tuple_index(supplying_receive, index=0) and combines it with io's existing token operand using a new after_all node.

Example:

// Original IR
chan test_channel(
  bits[32], id=0, kind=streaming, ops=send_receive,
  flow_control=ready_valid)

top proc main(__state: (), init={()}) {
  __token: token = literal(value=token, id=1000)
  receive.1: (token, bits[32]) = receive(__token, channel=test_channel)
  tuple_index.2: token = tuple_index(receive.1, index=0)
  tuple_index.3: bits[32] = tuple_index(receive.1, index=1)
  send.4: token = send(__token, tuple_index.3, channel=test_channel)
  after_all.5: token = after_all(send.4, tuple_index.2)
  tuple.6: () = tuple()
  next (tuple.6)
}

// Optimized IR
top proc main(__state: (), init={()}) {
  __token: token = literal(value=token, id=1000)
  receive.1: (token, bits[32]) = receive(__token, channel=test_channel)
  tuple_index.2: token = tuple_index(receive.1, index=0)
  tuple_index.3: bits[32] = tuple_index(receive.1, index=1)
  tuple_index.7: token = tuple_index(receive.1, index=0)
  after_all.8: token = after_all(tuple_index.7, __token)
  send.4: token = send(after_all.8, tuple_index.3, channel=test_channel)
  after_all.5: token = after_all(send.4, tuple_index.2)
  tuple.6: () = tuple()
  next (tuple.6)
}

Header

token_simp - Simplify token networks

Pass that simplifies token networks. For example, if an AfterAll node has operands where one operand is an ancestor of another in the token graph, then the ancestor can be omitted. Similarly, duplicate operands can be removed and AfterAlls with one operand can be replaced with their operand.

Note

What follows was generated by the Gemini LLM. Not human verified.

The TokenSimplificationPass simplifies the token dependency network within a function or proc. Token networks enforce ordering constraints between side-effecting operations (such as send, receive, and assert). By removing redundant token edges and canonicalizing min_delay annotations, this pass reduces control complexity and simplifies downstream scheduling.

If any node in the FunctionBase has a type containing more than one token (e.g., a tuple containing multiple tokens), the pass conservatively bails out without modifying the IR.

Otherwise, the pass executes a sequence of subpasses on after_all and min_delay operations:

  1. Simplifying min_delay Operations: * Trivial min_delay: A min_delay(tok, delay=0) is replaced with tok. Similarly, min_delay(after_all(), delay=X) on an empty after_all() is replaced with after_all().

      ```
      // Original IR
      min_delay.1: token = min_delay(tok, delay=0)
    
      // Optimized IR
      // Uses of min_delay.1 are replaced directly with tok.
      ```
    

    * Collapsing Nested min_delays: Consecutive min_delay operations are merged by summing their delays: min_delay(min_delay(tok, delay=1), delay=2) becomes min_delay(tok, delay=3).

      ```
      // Original IR
      min_delay.1: token = min_delay(tok, delay=1)
      min_delay.2: token = min_delay(min_delay.1, delay=2)
    
      // Optimized IR
      min_delay.3: token = min_delay(tok, delay=3)
      ```
    

    * Pushing min_delay Down Through after_all: If all operands of a non-empty after_all are min_delay nodes with positive delays, the minimum common delay d_min is factored out after the after_all, leaving residual min_delay(..., delay=d - d_min) nodes only for operands with d > d_min.

      ```
      // Original IR
      min_delay.1: token = min_delay(tok_a, delay=1)
      min_delay.2: token = min_delay(tok_b, delay=3)
      after_all.3: token = after_all(min_delay.1, min_delay.2)
    
      // Optimized IR
      min_delay.4: token = min_delay(tok_b, delay=2)
      after_all.5: token = after_all(tok_a, min_delay.4)
      min_delay.6: token = min_delay(after_all.5, delay=1)
      ```
    
  2. Simplifying after_all Operations: * Collapsing Nested after_alls: In reverse topological order, if an after_all node has no implicit uses and all of its users are also after_all nodes, its operands are flattened directly into each user after_all.

      ```
      // Original IR
      after_all.1: token = after_all(tok_a, tok_b)
      after_all.2: token = after_all(after_all.1, tok_c)
    
      // Optimized IR
      after_all.3: token = after_all(tok_c, tok_a, tok_b)
      ```
    

    * Pruning Overlapping (Ancestor) after_all Operands: If an after_all has operands x and y where x transitively depends on y through token-carrying nodes (conservatively stopping at invoke nodes so the pass is safe before function inlining, and bounding traversal by topological index), y is redundant and replaced by another operand of the after_all. * Deduplicating Operands: Duplicate operands in an after_all are removed (with remaining unique operands sorted by node ID). * Single-Operand after_all: An after_all(tok) with a single operand is replaced directly with tok.

      ```
      // Original IR
      send.2: token = send(tok, data, channel=ch)
      send.3: token = send(send.2, data, channel=ch)
      after_all.4: token = after_all(tok, send.2, send.3)
    
      // Optimized IR
      // tok and send.2 are ancestors of send.3; after pruning,
      // deduplication, and single-operand removal, after_all.4 is
      // replaced directly with send.3.
      ```
    

If any simplification modifies the IR, CollapseMinDelay is run one final time to merge any min_delay operations that became adjacent after after_all removal.

Header

useless_assert_remove - Remove useless (always true) asserts

Pass which removes asserts that have a literal 1 as the condition, meaning they are never triggered. Rewires tokens to ensure nothing breaks.

Note

What follows was generated by the Gemini LLM. Not human verified.

The UselessAssertRemovalPass eliminates assert operations whose condition is statically known to be true (1), since such assertions can never fail at runtime or in simulation.

How it Works:

  1. Condition Analysis: The pass traverses the IR in topological order and queries a StatelessQueryEngine (KnownValueAsBits) on each assert node's condition operand.
  2. Token Rewiring and Removal: If the condition is known to be 1 (IsOne()), all uses of the assert node's output token are replaced directly with the assert's input token operand, and the assert node is removed from the FunctionBase.

Example:

// Original IR
fn f(tkn: token) -> token {
  literal.1: bits[1] = literal(value=1)
  ret assert.2: token = assert(tkn, literal.1, message="always passes")
}

// Optimized IR
fn f(tkn: token) -> token {
  ret tkn
}

Header

useless_io_remove - Remove useless send/receive

Pass which removes sends/receives that have literal false as their condition. Also removes the condition from sends/receives that have literal true as their condition.

Note

What follows was generated by the Gemini LLM. Not human verified.

The UselessIORemovalPass simplifies predicated send and receive operations across all procs in a Package when their predicate operand is statically known to be 0 (false) or 1 (true) according to a StatelessQueryEngine.

First, the pass builds a package-wide map (ComputeChannelMaps) tracking all send and receive operations associated with each ChannelRef. It then traverses each proc in topological order and applies the following transformations to predicated I/O nodes:

  1. Removal or Simplification of False-Predicated I/O (predicate == 0): * send with predicate == 0: * If there is at least one other send remaining on the same channel, the disabled send is removed and its uses are replaced with its input token operand. * If it is the last send on that channel, removing it would leave the channel without a sender. Instead, the send is kept and its data operand is replaced with a zero literal (ZeroOfType) so dead upstream data computation can be removed. * receive with predicate == 0: * If there is at least one other receive remaining on the same channel, the disabled receive is removed and replaced with a tuple containing (token, zero_data) for blocking receives, or (token, zero_data, 0) (with a 0 valid bit) for non-blocking receives.

    // Original IR (assuming another send exists on my_chan)
    literal.1: bits[1] = literal(value=0)
    send.2: token = send(tkn, data, predicate=literal.1, channel=my_chan)
    
    // Optimized IR
    // Uses of send.2 are replaced directly with tkn.
    
  2. Simplification of True-Predicated I/O (predicate == 1): If a send or receive has a predicate known to be 1, the redundant predicate operand is stripped, converting the operation into an unpredicated send or receive on the same channel.

    // Original IR
    literal.1: bits[1] = literal(value=1)
    receive.2: (token, bits[32]) = receive(tkn, predicate=literal.1,
        channel=my_chan)
    
    // Optimized IR
    receive.3: (token, bits[32]) = receive(tkn, channel=my_chan)
    

Header