Early exits are constructed directly in FastData IR through IEarlyExit.GetCondition, EarlyExitPlan, and EarlyExitLowerer. Custom exits use the same IR contract. Hash functions are constructed directly in FastData IR and compiled to IL for build-time evaluation; HashProgramImporter rebinds that IR into the lookup program. Language backends render the resulting portable operations. See Hashing.
Backend preparation resolves builtins and helpers. Renderers then implement language-specific arithmetic and memory operations while preserving the IR contract. There is no template compiler or raw source escape in the frontend lowering pipeline.
Functional lowering tests live in FastData.Generator.Tests; portable semantics are covered in FastData.Library.Ir.Tests. The native IR harness compiles and runs real generated hash functions and early exits in all three languages.
Shared preparation keeps referenced data, exports, and public lookup storage. Data IDs and names stay stable. Directly supplied IR keeps all declarations.
IrOptimizer in FastData.Library.Ir.Optimization optimizes an IrProgram or standalone IrFunction. Simplify reduces a standalone expression without introducing locals. Optimization preserves signatures, data, records, and the input's immutable ownership contract. Parameters and the function's own locals keep their variable IDs. Optimizer-created temporaries are appended after them, and the temporaries that survive are renumbered densely, so a temporary's ID is not stable across optimizer versions and unused ones disappear. Unchanged nodes are retained.
Hash generators build raw IR through HashBuildContext. Its completion stage runs the generic optimizer before counting nodes/operations, fitness evaluation, compilation, and benchmarking. The same optimized hash is imported into lookup IR. CodeGenerator optimizes complete lookup programs before backend preparation, covering generated structures and directly supplied lookup programs as well.
The reduction families from the expression-tree optimizer are supported in their IR forms: literal and conversion folding; arithmetic, bitwise, and shift identities; unsigned constant reassociation; constant/self/extreme-value comparisons; duplicate/opposing conditions and comparison ranges; Boolean identities, annihilation, idempotence, complements, absorption, association, gathering, factoring, distribution, De Morgan, double negation, and tree balancing. A bounded reduced ordered decision diagram handles Boolean algebra. Constant branches and Boolean-returning conditionals are simplified as statements. CLR member/initializer/conditional expression nodes have no direct IR counterpart: immutable literal fields and array elements are folded, while value selection remains statement based.
The reducer avoids reassociating signed arithmetic and preserves NaN behavior and text encoding. Rewrites that drop or reorder evaluation require pure, total work. IrValueRange caches conservative bounds for shift counts, divisors, and signed results. It also tracks integral conversions and constant unsigned offsets that fit one interval. Proven bounds can fold comparisons. The reducer balances short-circuit chains, keeps required evaluations of shared nodes, groups comparable bounds, and drops unreachable terms. BooleanAtomLimit and BooleanNodeLimit bound algebraic minimization.
CSE uses structural expression identity within each eager evaluation region, introducing temporary assignments for repeated computations of at least two operations (conversions are free and calls always qualify), so a repeated cast or single addition is recomputed rather than stored. This statement-local CSE never reuses a temporary across statements or iterations; the cross-statement pass below reuses stored values. Short-circuit operands retain their guards; condition temporaries for loops are recomputed at every test, including after continue. Unknown extension expressions remain opaque. Operands of commutative operations are canonical in two ways. The reducer moves a literal to the right of integral Add, Multiply, And, Or and Xor and of any Equal or NotEqual, and swaps a literal-left ordered comparison with its operator reversed (3 < x becomes x > 3); ordered floating-point comparisons are left alone. Interning treats op(a, b) and op(b, a) as one node when both operands are discardable and neither is a literal, so x * 3 + y and y + x * 3 share a temporary. Operands that may trap or have effects keep their order and identity.
The shared optimizer can replace a bounded bitmap with equality or masked equality. It can remove gap checks when the bitmap already rejects the gap. Range propagation uses a successful masked equality to recover bounds.
The optimizer runs statement reduction, forward propagation and reuse, range propagation, loop-invariant hoisting, and dead-store elimination for up to four rounds or until the body stabilizes. Passes share block summaries. Statement reduction prunes unreachable statements before reuse and hoisting. Unused temporaries are then removed and the rest renumbered.
- Forward propagation and reuse. The pass tracks scalar copies and reusable computations together. Writes invalidate facts that depend on the assigned variable. Nested blocks inherit those facts and discard local changes on exit.
- Range propagation. Comparisons and bitmap tests refine bounds along each path. Assignments replace facts, and loop writes invalidate them at the header and exit. Proven bounds can fold comparisons and values.
- Loop-invariant code motion. The pass hoists sufficiently costly, pure and total expressions whose inputs stay unchanged in the loop. Unknown effects in the loop prevent call hoisting. Inner loops run through the pass first.
- Dead-store elimination. Reads follow reaching definitions through branches and loops. The pass removes unread local stores of pure and total expressions, while preserving parameter stores.
Statement-local CSE materializes a partial expression into a temporary only when no partial work remains inline ahead of it. The passes never reorder evaluation, and expressions that are not pure are never copied, merged or moved, and only pure and total expressions are ever hoisted out of a loop. A differential fuzzer (IrOptimizerFuzzTests) compares results, traps and the order of unknown calls before and after optimization on random programs that reassign variables across statements, branches and loops.
The test-only SMT verifier retries inconclusive bounded cases in a fresh Z3 context, translating each complete case formula together to preserve declaration identities. It keeps both the original case with explicit predicate bindings and its substituted form, and applies SSA elimination with an alternative Boolean AIG canonicalization strategy before congruent arithmetic abstraction. Exact unsigned-remainder range reductions remove impossible high bits without constraining the dividend. Arithmetic refinement adds one equation at a time; SAT still requires validating every reachable operation, including dependencies hidden by shared arithmetic symbols. Only UNSAT discharges a case, and every remaining case, trap/effect comparison and cutoff obligation is still checked. Transformed SAT models never become IR counterexamples. Verifier fuzzing checks both preprocessing strategies and isolated recovery against independent complete enumeration, reporting unresolved optional proof attempts separately. Certificate callbacks receive read-only formal argument views, and each finite-query translation owns independent caches. The formula enumeration oracle requires every substituted premise to become a Boolean literal, including premises on rejected rows. Z3 remains test-only.
Structural support checks and call-graph SCC discovery use iterative traversals with invocation-local caches for shared expression, function, block and type graphs. Program validation visits a shared expression once within one evaluation; its cache never crosses assignment states, branches or functions. Boolean chain flattening removes repeated pure subgraphs, while repeated effectful subgraphs retain their original sharing and evaluation count instead of being expanded into a tree.
The SMT encoder skips a callee only when its execution path simplifies to false, retaining earlier argument traps and effects. Cached call-free outcomes are encoded over the full domain, independent of the first caller's guard. Ordinary function checks avoid constructing aggregate inputs that neither version reads or writes; inductive certificate formals remain explicit. Native datatype setup rejects layouts with more than 4096 expanded structural nodes before asking Z3 to construct them. Call expansion and aggregate well-formedness each have a 65,536-step setup limit, and recursive encoding uses catchable stack guards. Exceeding a setup limit reports UNKNOWN or inductive Inconclusive, never equivalence, a full proof, or an IR trap. Bounded Boolean cases continue after an inconclusive case so later counterexamples can still be found. No partial formula is submitted as a completed proof obligation.
IR snapshot diagnostics separately limit traversal to 4096 steps and output to 65,536 characters, with an explicit omission marker when a limit is exceeded. These diagnostic limits do not restrict verification inputs or solver queries. Existing per-solver-check timeouts remain separate from setup resource guards.
The optimizer fuzzer keeps reference-interpreter comparisons for the original program and both optimization runs. A test-only execution copy adds fuel checks at function entry and loop-body entry; exhaustion fails with the seed, program, input and optimization label, and is never treated as an IR trap or a proof. The same budget protects interpreter/SMT replay. Loop replay binds each concrete input before bounded encoding and checks results, traps, ordered effects and absence of a cutoff; the separate symbolic optimization comparisons still cover the full input domain. Each execution gets a fresh external environment: unknown calls return invocation-dependent values, while pure and total fixtures remain stateless. Replay explicitly identifies source executions: only those receive expression read-stability assumptions. Optimized targets retain the source model's freedom to regroup reads around effects. Read-only defined helpers inherit the enclosing source expression's stability region; effectful callees retain their own statement boundaries. This classification walks the bodies and external contracts independently of optimizer analysis.
External replay records callable slots directly from interpreter dispatch. The interpreter's IrExternalSlotHandler overload supports independent implementations for different slots sharing one declaration object; the original declaration-only handler remains available. SMT case splitting continues after UNKNOWN or a bound-exhaustion result to look for a definite counterexample. SAT takes precedence, while equivalence still requires every required case, comparison and coverage check to be discharged. Direct compositional checks enforce the same text-encoding, record-layout and external-identity compatibility as the wrapper. Symbolic packed String arrays reserve the terminal offset entry, limiting their element count to Int32.MaxValue - 1.
Arithmetic coverage counts reachable applications actually abstracted in completed queries, with product counts, widths and degree, rather than strategy selection or solver retries. The arithmetic campaign requires a completed deep-product proof and a coarse SAT model refuted to UNSAT by refinement. Independently enumerated wide-bit-vector queries guarantee those paths; the history/completion campaign does not claim arithmetic coverage from its two-bit inputs.
Verifier fuzzing also compares complete witness sets. Stable Boolean/bit-vector input observations survive SSA and AIG preprocessing; concrete row bindings are applied after each whole query is translated. Every enumerated row is checked against the original, finite, exact arithmetic, SSA and AIG encodings. Program rows include both feasibility of the correct return/trap/result and exclusion of any disagreement, as well as pairwise difference membership. History rows include both formula polarities and inconsistent same-key completions, with explicit finite codes preserving all completion classes. Existing unbound queries, adaptive arithmetic refinement and interpreter comparisons remain in place.
Required complete-byte-domain programs exercise fourth-Boolean-dependent counterexamples through both public drivers, plus nonlinear loops with partial arithmetic, break and continue after optimization once and twice. An additional bounded comparison uses the original encoder with congruent arithmetic abstraction and requires an observed deep-product SAT-to-UNSAT refinement; this retains the same result, trap, effect and cutoff obligations. The default optimized encoding is still checked separately. Four generated prefix programs in each optimizer-fuzz seed guarantee live source loops, break/continue, unknown/pure/total calls and an external trap. Coverage comes from reference-execution events, so unreachable syntax cannot satisfy it.
External calls are conservative by default. IrOptimizerOptions.FunctionEffects supplies IrFunctionEffects.Pure for deterministic, effect-free functions whose reads remain stable during expression evaluation. Pure | Total additionally promises termination without exceptions for every argument, allowing evaluation to be removed or reordered. Defined functions are analyzed from their bodies; recursion is conservative. Unknown effects prevent sharing and hoisting within the affected eager region. Hash read helpers and lookup builtins declare purity without totality, preserving their access preconditions.
IrOptimizerOptions options = new IrOptimizerOptions
{
FunctionEffects = id => IsKnownRead(id) ? IrFunctionEffects.Pure : IrFunctionEffects.None
};
IrProgram optimized = IrOptimizer.Optimize(rawProgram, options);Optimizer tests check IR shape and equivalence. The Boolean suite checks 20,000 expressions and snapshots the first eight in Src/FastData.Library.Ir.Tests/Verify/IrOptimizer.