Skip to content

Inlining in the compiler: current state and proposed changes #8733

Open

Description

@cknitt

"Inlining" in the compiler covers four different features that share one attribute name (@inline). They move through the pipeline in different ways and are stored in different build files. This issue describes how each works today, lists the problems found, and proposes what to change, as context for #8689 and the @inline item in #8624.

Updated 2026-11-28 after a review by Claude (Fable model) against master e51ee46 and #9467: new problems 2.8–2.11 and repro 4 in 2.1, a single meaning for @inline (proposal 3), and an ordered PR plan (section 6). Paths now point at compiler/backend, compiler/typing and build_system/.

TL;DR

# Feature How it's written What it means Stored in The build system notices a change?
A Inline constants @inline let x = 1 / @inline(1) let x: int Changes the interface: the value is part of the signature .cmi ✅ (the .cmi changes)
B Externals external f: … = "…" The FFI call is emitted directly at each call site .cmi ✅
C Function inlining inside one module Automatic, or @inline / @inline(never) on a function Optimization hint Nowhere; happens during compilation n/a
D Cross-module value and function inlining Automatic (true/false/null/undefined); functions only with -bs-cross-module-opt Optimization .cmj ❌ can go stale: inlined values, and whether the module has side effects

Feature A was handled by a frontend rewrite; #9467 moves it into the type checker. Feature D has a correctness bug in incremental builds (2.1) and two bugs in what it exports (2.8, 2.9). #8689 extends D with an explicit opt-in. The proposed model (proposal 3) drops that opt-in: @inline on an exported function exports its body.

1. How the pipeline works today

A. Inline constants (@inline let / @inline(lit) let)

  1. Parser: @inline is kept as a plain attribute. In an implementation the value is the right-hand side (@inline let x = 1). In an interface it's the attribute payload (@inline(1) let x: int).

  2. Type checker (with Type @inline constants in the type checker, keep their attributes and allow annotations #9467): Typedecl.transl_value_decl reads @inline(<literal>) on a value in a signature, and the Pstr_value case in Typemod reads @inline let x = <literal>, also with a type annotation that is the literal's type, possibly through an alias. Both build Val_prim {prim_kind = Kind_inline_const c} and keep the value's other attributes.

    On master, the frontend (bs_builtin_ppx.ml) still rewrites such a binding into a fake external with a reserved primitive name, drops its other attributes, and the type checker decodes it again. Type @inline constants in the type checker, keep their attributes and allow annotations #9467 removes that rewrite and the reserved name.

  3. Annotated bindings (@inline let x: int = 3) are inline constants with Type @inline constants in the type checker, keep their attributes and allow annotations #9467. On master they are ordinary values with warning 53.

  4. Translation: translcore (transl_external_application) replaces each use with Lconst (lambda_of_inline_const c).

  5. Build files:

    • .cmi: the constant itself, inside the value's Val_prim primitive description. Any change to the value changes the .cmi, so dependents are rebuilt correctly.
    • JS: nothing. A primitive doesn't produce a JS binding, so @inline constants are not exported from the generated module (for example, tests/tests/src/inline_const.mjs doesn't export f, f1, f5, f6). JS or genType consumers can't import them.
  6. Interface matching: Primitive.coercible requires the same kind. An interface @inline(1) let x: int can only be satisfied by an @inline implementation with the same value. A plain let x = 1 doesn't match it, while an @inline implementation can be hidden behind a plain let x: int. It then gets a normal JS binding, and dependents use A.x instead of the constant: for A, the .resi decides what is inlined.

B. Externals

These follow the same path as A, with Prim_ffi → Kind_external spec. The full FFI spec is stored in the .cmi, so every call site emits the JS call directly.

Exception: when an external's module path is package-relative (@module("./foo")), Ast_external_process sets no_inline_cross_module. The interface then gets a plain val, and the implementation is wrapped in include (… : sig val … end). Other modules call through an ordinary exported binding, because the relative path only works from the declaring file.

C. Function inlining inside one module

  • Attributes: Translattribute reads @inline / @inline(always) / @inline(never) on a function expression or binding and stores it as Lfunction.attr.inline (Always_inline | Never_inline | Default_inline). @inline on anything that isn't a function gives warning 53 ("misplaced attribute").
  • Optimizer: Lam_pass_remove_alias does the beta reduction (substituting the arguments into the function body). Lam_analysis.ok_to_inline_fun_when_app decides when:
    • Always_inline → always inline; Never_inline → never.
    • Default_inline → inline when the body size is under 5 (small_inline_size), when the call can be resolved statically via destruct_pattern, or when all arguments are constants, the size is under 10, and the body has no side effects.
    • Async functions and functions with a directive are never inlined (lfunction_can_be_inlined).

D. Cross-module inlining via .cmj

Export (Lam_stats_export.values_of_export). For each exported value, the .cmj stores {name; arity; persistent_closed_lambda}, where the last field is a Lambda term (the compiler's intermediate representation) that callers can copy:

  • true / false / null / undefined constants are always exported, whatever the flags.

  • Everything else is only exported when -bs-cross-module-opt is set (off by default; can be set through compiler-flags). Even then, only values that pass safe_to_inline are exported:

    • functions;
    • constant constructors and polymorphic variants, booleans, undefined.

    Ints and strings are never exported. Functions qualify under one of two rules:

    • @inline functions and functors: exported only when closed (Lam_closure.is_closed), i.e. they don't capture any surrounding local values.
    • Other functions: exported when the size is under 5 and there are no free variables.
  • Js_cmj_format.get_result filters again when the .cmj is read: unless the flag is set, everything except the four constants is dropped.

  • None of this depends on the interface. With an A.resi declaring let flag: bool, dependents still get true copied in. The .resi only decides which values are exported; their stored bodies come from the implementation. The same holds for functions under -bs-cross-module-opt.

Use. Lam_compile_env.query_external_id_info looks up the other module's .cmj entry:

  • Lam_pass_remove_alias beta-reduces A.f(args) with the stored body.
  • Lam_compile.compile_external_field emits stored non-function constants directly.
  • compile_external_field_apply inlines stored functions during code generation.

Format. The .cmj is a 16-byte digest header followed by the marshalled data. to_file ~check_exists skips rewriting the file when its content is unchanged.

Observed with a two-module project (B uses A's values):

  • With no flags, let flag = true in A is copied into B as let f = true. let num = 1 and all functions are referenced as A.num / A.g(3), even @inline let g = ….
  • With -bs-cross-module-opt, both @inline let g = x => x + 1 and the unannotated let h = x => x * 2 were inlined (let a = 4; let b = 6).

Summary: what each build file stores

File Inlining-related contents The build system rebuilds dependents when it changes?
.cmi Types, plus Val_prim descriptions: the full FFI spec for externals (B) and the literal for @inline constants (A). Also declaration locations. Yes. This is the only signal the build system uses today: publish_compiler_artifacts in build_system/compiler_process.ml reports Cmi_changed, and Build_state.record_published_cmi marks dependents dirty.
.cmj Per exported value: arity, plus an optional persistent_closed_lambda (D: always-exported bool/null/undefined constants, plus small or @inline closed functions under the flag). Also effect information and hoisted exports. No on master; publish_compiler_artifacts only checks that it exists. #8689 adds this.
.js The generated code. @inline constants and externals produce no binding. n/a

2. Problems

2.1 Stale JS after incremental builds (bug on master)

A dependent reads A's .cmj (copied values, arity, and whether A has side effects), but the build system only checks A's .cmi.

Repro 1 (no flags):

// A.res
let flag =  true   // two spaces, so the edit below keeps every location
let num = 2

// B.res
let f = A.flag

Build, then change A to let flag = false and build again. Only A is recompiled. A's .cmi is byte-identical, A.mjs has let flag = false, but B.mjs still has let f = true.

Repro 2 ("compiler-flags": ["-bs-cross-module-opt"]):

// A.res
let h = x => x * 2

// B.res
let b = A.h(3)

Build, then change the body to x * 3. Only A is recompiled, and B.mjs still has let b = 6.

Repro 3 (any module with a .resi, no flags):

// A.resi
let flag: bool

// A.res
let flag = true

// B.res
let f = A.flag

Build, then change A.res to let flag = false. A.cmi is built from the .resi alone, so it stays byte-identical even when every line of A.res moves. B is never rebuilt and keeps let f = true.

For modules without an interface, the bug is mostly hidden in practice because the .cmi stores declaration locations, so most edits shift something and trigger the rebuild by accident. Modules with a .resi don't have this safety net: every change of such a value leaves dependents stale. #8689's .cmj digest check fixes this as a side effect.

Repro 4 (no flags, not about inlining): with the A.resi and B.res of repro 3, add Console.log("effect") to A.res. Only A is compiled. B.mjs keeps /* No side effect */ and still has no import of A.mjs, so the effect never runs when B is A's only importer. Dependents read the "pure" bit from the .cmj (Lam_compile_env.is_pure_module), and B's own bit is then stale too. So the whole .cmj is an input of every dependent, not only its inlinable part.

2.2 @inline means three things

@inline is a signature-level constant (A), an optimization hint (C), and with #8689 an opt-in for cross-module inlining (D). Which one applies depends on whether the right-hand side is a literal, which is easy to get wrong. For example, @inline let x: int = 3 silently became an ordinary value with warning 53 (fixed in #9467).

2.3 Inline constants are a frontend rewrite, not part of the AST

Also tracked in #8624. Status of each problem:

2.4 @inline constants are missing from the JS output

That's expected for externals, but surprising for something written as let, and it limits interop. Two consequences:

2.5 @inline on a function does nothing across modules by default

Without the global flag nothing is exported to .cmj. The global flag, meanwhile, inlines every small closed function, opted-in or not.

2.6 The global -bs-cross-module-opt flag isn't a clear contract

It applies per compiler invocation, its export rules are an internal heuristic (size < 5), and nothing documents it. #8689 makes cross-module inlining an explicit per-function choice, which would make the global flag largely redundant.

2.7 The .cmj is not governed by the interface

true/false/null/undefined values are copied into dependents even when the .resi only promises a type. Arity and purity also come from the implementation, whatever the .resi says. This is safe once 2.1 is fixed: every package is compiled from source by its consumer, so a .resi is a typing boundary, not a binary one. No change proposed. Dropping the four constants would quietly turn if A.debug in dependents from dead code into a runtime check.

2.8 Exported bodies can contain relative-path externals

With -bs-cross-module-opt, a body that calls a @module("./helper.js") external is inlined into a module in another directory, which then imports ./helper.js relative to itself. Example: src/ffi/Hidden.res with @module("./helper.js") external raw: int => int = "raw" and @inline let wrapped = x => raw(x) + 1; src/app/B.res calling Hidden.raw(1) and Hidden.wrapped(1) gets import * as HelperJs from "./helper.js". The type checker's guard (Primitive.no_cross_module_inline and the include wrapper in typemod.ml) is undone by the backend, because the wrapper is a small closed function and is exported. #8689 has no check for this either.

2.9 Exported bodies can name modules the caller cannot load

If an exported body refers to a module C that the caller cannot see (for example a module of a package the caller does not depend on), inlining it fails with "C not found, it means either the module does not exist or it is a namespace". Reproduced by hiding C from the include path; the two-package case has not been built yet.

2.10 Stored bodies carry locations

Stored Lambda bodies keep Location.t (lfunction.loc, ap_loc, prim_info.loc), and -no-keep-locs does not cover them. So a line shift changes the .cmj, and the runtime's lib/rescript/*.cmj, which are published (lib is in the package's files), contain absolute build paths. The runtime is built with -bs-cross-module-opt. With default flags the .cmj holds no bodies: it is about 100 bytes and keeps its digest across line shifts and body edits.

2.11 Payloads on constants are ignored

@inline(3) let x = 4 is the constant 4, and @inline(never) let x = 5 is an inlined constant, both without a warning. module type S = { @inline(never) let q: int } is accepted silently. Separately, an @inline constant in a signature isn't checked against its type (#9468).

3. Related work

4. Proposals

  1. Rebuild dependents when a module's .cmj changes, independently of Add opt-in cross-module inlining for Option helpers #8689 (its build-system part). The whole .cmj is the right unit: dependents read almost every field (2.1, repro 4), so a separate digest of only the inlinable data buys nothing. With default flags the .cmj changes only when an exported arity, the purity, one of the four constants or the package spec changes, and each of those changes dependents' JS. A rebuild stops at the first dependent whose own .cmi and .cmj are unchanged. Stripping locations from stored bodies (2.10) keeps a line shift from rebuilding the direct dependents of a module with a .resi.
  2. Give inline constants a structural form (feature A). Done differently in Type @inline constants in the type checker, keep their attributes and allow annotations #9467. The original plan was a Prim_inline constructor in primitive_repr, produced by the parser. Resolve FFI externals during type checking #8728 made pval_prim a plain string again and kept FFI attributes as attributes that the type checker reads. Type @inline constants in the type checker, keep their attributes and allow annotations #9467 does the same for @inline: no parsetree change, and PPXs keep seeing the attribute as written (the rewrite always ran after them). Type @inline constants in the type checker, keep their attributes and allow annotations #9467 also inlines annotated constants, so nothing from 2.3 is left.
  3. One meaning for @inline: uses are replaced by the definition, in this module and in others.
    • On a literal let: a signature constant (A), as Type @inline constants in the type checker, keep their attributes and allow annotations #9467 implements it.
    • On a function or functor: every saturated call is inlined (C). If the value is exported and exportable, its body is stored in the .cmj and inlined in other modules too (D), with or without a flag.
    • @inline(never): never inlined and never exported.
    • No @inline(crossModule). A fourth payload would make 2.2 worse, and the flag already gives @inline this meaning for functions and functors.
    • Exportable means closed, not async, no directive, and no call to a relative-path external (2.8). A non-exportable @inline function is inlined only in its own module, without a warning, so existing code keeps compiling.
    • At the use site, a stored body is inlined only when every module it names can be loaded; otherwise the call stays a normal call (2.9).
    • The .resi controls types and @inline constants (they are Val_prim in the .cmi), not bodies, the four constants, arity or purity (2.7).
    • Cost: existing @inline functions start exporting bodies, which changes the JS of their dependents. Fine for a major version.
  4. Remove -bs-cross-module-opt once the stdlib helpers that rely on it are annotated with @inline. Keep the four always-exported constants (2.7). For one release, accept the flag and ignore it with a warning.
  5. Export @inline constants to JS by making them ordinary values whose literal is also known in their value description. Coercing one to a plain let is then the identity, module objects contain the field, and genType needs no special case (2.4). Ideally in the same release as Type @inline constants in the type checker, keep their attributes and allow annotations #9467, so the lost exports of annotated constants never ship.

5. Open questions

  • Should a non-exportable @inline function on an exported binding warn?
  • Is losing source-map positions inside inlined bodies acceptable, in exchange for stable .cmj files (2.10)?
  • Should the "pure" bit, arity and the four constants keep coming from the implementation when a .resi exists (2.7)? Proposed: yes.

6. PR plan

  1. Strip locations from stored bodies (2.10; Leave source locations out of bodies stored in .cmj files #9470). First, so that PR 2 doesn't rebuild the direct dependents of a module with a .resi on every line shift when bodies are stored. Breaks source-map positions inside inlined bodies. Tests: the .cmj digest survives a line shift; no absolute paths in the runtime's .cmj files.
  2. Rebuild dependents when the .cmj changes (build_system/ only; proposal 1). Tests: integration tests (tests/build_tests/integration) for repros 3 and 4, a unit test in tests/build_tests/unit/compiler_process_tests.ml, and the allocation benchmarks for edits in generated projects.
  3. Never export a body that calls a relative-path external (lam_stats_export.ml; 2.8). Test: the 2.8 layout with the flag.
  4. Fall back to a normal call when a stored body names a module that cannot be loaded (lam_pass_remove_alias.ml, lam_compile.ml; 2.9). Test: a two-package build test with an undeclared transitive dependency.
  5. @inline on an exported function or functor exports its body, flag or not, and the Option helpers are annotated (proposal 3; replaces the compiler part of Add opt-in cross-module inlining for Option helpers #8689). Breaks: the JS output of dependents of existing @inline functions. Tests: Add opt-in cross-module inlining for Option helpers #8689's tests with @inline.
  6. Diagnostics: warn on a payload on an @inline constant (2.11), warn on @genType on an @inline constant until proposal 5 lands, and check signature constants against their type (@inline constants in signatures are not checked against their type #9468).
  7. Remove -bs-cross-module-opt (proposal 4): first drop it from the runtime and Belt rescript.json and review the lib/es6 diff, annotate what regresses, then remove the flag, the read-side filter in Js_cmj_format.get_result and the size heuristic in Lam_stats_export.
  8. Export @inline constants to JS (proposal 5).

Optional and cosmetic: accept a local @inline let inside a function, and stop parsing @inlined only to warn about it.

Activity

  1. added a commit that references this issue on Oct 8, 2026
  2. added a commit that references this issue on Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions