Skip to content

perf(variant): collapse trivial-destructor / trivial-copy thunks (#3249 / #3244 Tier 3G) - #3266

Merged
zackees merged 1 commit into
masterfrom
feat/3249-variant-trivial-thunks
Jun 19, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3249-variant-trivial-thunks

Conversation

@zackees

@zackees zackees commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Two-axis collapse of the per-(variant × T × op) thunk explosion in fl::variant<Ts...>:

  1. Namespace extraction. Thunks move out of variant<Ts...> into fl::detail:: namespace scope. Previously each variant instantiation had its own mangled variant<Types...>::destroy_fn<T> / copy_fn<T> / move_fn<T> symbols; now typed_destroy_thunk<T> / typed_copy_thunk<T> / typed_move_thunk<T> are shared across every variant instantiation containing T.

  2. Trivial collapse. Trivially-copyable T's collapse further to a single shared variant_noop_destroy + per-size variant_trivial_copy_n<sizeof(T)> / variant_trivial_move_n<sizeof(T)> thunks. All bool, i64, float, nullptr_t, etc. alternatives across every variant in the link now share one noop-destroy and a handful of size-keyed memcpy bodies.

visit_fn<T, Visitor> stays per-(T × Visitor) -- it dispatches into the visitor's typed operator()(T const&) and the collapse would change behavior. Out of scope per acceptance.

Trait choice

The issue body called for is_trivially_destructible<T> as the gate. That trait is not in fl/stl/type_traits.h; is_trivially_copyable<T> is used instead. Per the C++ standard, trivially-copyable implies trivially-destructible, so the destroy collapse is correctness-preserving (slightly more conservative than the issue's wording but captures every primitive alternative the audit named in json_value's bool / i64 / float / nullptr_t).

Flash impact (LPC845-BRK / AutoResearch)

Metric Master Branch Delta
Flash (.bin) 46,840 B 46,404 B -436 B
ELF .text 135,160 B 130,692 B -4,468 B
Flash % of 64 KB 71.5% 70.8% -0.7%
Per-variant thunk symbols (variant<...>::destroy_fn/copy_fn/move_fn) 55 0 structural collapse

Honest caveat re acceptance bullet ≥ 800 B net flash drop

The 436 B drop is below the acceptance target. Same documented pattern as #3258 (#3246) and #3261 (#3251) before it: AutoResearch's LowMemory mode exercises only ~3 distinct variant<...> instantiations against json_value's 10-alternative variant, so the audit-predicted 2-3 KB (which assumed json-heavy Large-memory builds) only partially materializes here.

The structural collapse is verified -- 55 per-variant thunk symbols in master → 0 in branch; everything is routed through the shared namespace-scope thunks (verified via llvm-nm symbol diff in the commit body).

Test plan

  • bash test --cpp -- 330/330 unit tests pass.
  • bash test variant -- variant-specific tests pass; semantics preserved.
  • bash lint --cpp -- 0 violations.
  • LPC845-BRK / AutoResearch host-cross build green (flash 70.8% < 71.5% baseline).
  • llvm-nm symbol audit shows the 55 old variant<...>::destroy_fn/copy_fn/move_fn symbols are gone and the typed_destroy_thunk<T> / typed_copy_thunk<T> / typed_move_thunk<T> shared symbols + per-size variant_trivial_copy_n<N> thunks are present.

Files

  • src/fl/stl/variant.h -- 114 added, 33 removed (1 file modified)

Refs #3249, #3244 (Tier 3G), #3235.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Restructured variant's internal lifetime management with improved dispatch mechanisms for copy, move, and destroy operations. Optimized handling of trivially-copyable types.

… / #3244 Tier 3G)

Two-axis collapse of the per-(variant x T x op) thunk explosion in
`fl::variant<Ts...>`:

1. Thunks moved out of `variant<Ts...>` into `fl::detail::` namespace
   scope. Previously each variant instantiation had its own mangled
   `variant<Types...>::destroy_fn<T>` / `copy_fn<T>` / `move_fn<T>`
   symbols; now `typed_destroy_thunk<T>` / `typed_copy_thunk<T>` /
   `typed_move_thunk<T>` are shared across every variant instantiation
   that contains `T`.

2. Trivially-copyable T's collapse further to a single shared
   `variant_noop_destroy` + per-size `variant_trivial_copy_n<sizeof(T)>`
   / `variant_trivial_move_n<sizeof(T)>` thunks. All `bool`, `i64`,
   `float`, `nullptr_t`, etc. alternatives across every variant in the
   link now share one noop-destroy and a handful of size-keyed memcpy
   bodies.

`is_trivially_copyable<T>` is the gate. Per the C++ standard
trivially-copyable implies trivially-destructible, so the destroy
collapse is correctness-preserving. The issue body called for
`is_trivially_destructible` -- we don't have that trait in
`fl/stl/type_traits.h` yet; `is_trivially_copyable` is slightly more
conservative but captures every primitive alternative the audit named
(json_value's bool / i64 / float / nullptr_t).

`visit_fn<T, Visitor>` stays per-(T x Visitor) -- it dispatches into
the visitor's typed `operator()(T const&)` and the collapse would
change behavior. Out of scope per acceptance.

Flash impact (LPC845 / AutoResearch):
  - Master baseline: 46,840 B
  - This branch:     46,404 B
  - Delta:           **-436 B** flash, **-4,468 B** ELF .text
  - Per-variant thunk symbols: 55 -> 0 (all routed through shared
    namespace-scope thunks)

The 436 B flash drop is below the 800 B acceptance target. Per the
meta #3244 lesson-learned: AutoResearch exercises only 2-3 distinct
variant<...> instantiations against json_value's 10-alternative
variant; the audit's predicted 2-3 KB assumes json-heavy
Large-memory builds. The structural collapse is correct and the
infrastructure is in place to compound with the next tier of
variant-heavy sketch. Test coverage (variant unit tests + the json
parsing path that exercises the trivial alternatives) is green.

Refs #3249, #3244 (Tier 3G), #3235.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

src/fl/stl/variant.h adds a fl::detail namespace with type aliases, per-type thunk function templates, shared trivially-copyable memcpy-based thunks, and compile-time picker functions. Inside variant, destroy_current, copy_construct_from, and move_construct_from are rewritten to dispatch through static constexpr function-pointer tables populated by those pickers.

Changes

Variant lifetime thunk collapsing

Layer / File(s) Summary
fl::detail thunk declarations and picker functions
src/fl/stl/variant.h
Adds fl/stl/cstring.h include and introduces fl::detail namespace with variant_destroy_fn/variant_copy_fn/variant_move_fn type aliases, typed_destroy_thunk<T>/typed_copy_thunk<T>/typed_move_thunk<T> per-type templates, shared variant_noop_destroy and size-keyed variant_trivial_copy_n<N>/variant_trivial_move_n<N> memcpy thunks, and pick_variant_destroy_fn<T>()/pick_variant_copy_fn<T>()/pick_variant_move_fn<T>() compile-time pickers.
variant static dispatch table rewire
src/fl/stl/variant.h
Replaces variant-scoped per-type destroy_fn/copy_fn/move_fn templates with static constexpr function-pointer arrays populated from fl::detail::pick_variant_*_fn<Types>(), updating call signatures in destroy_current, copy_construct_from, and move_construct_from while preserving _tag - 1 indexing and other.reset() after move.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

🐇 Hoppity hop through the variant maze,
Where thunks once bloomed in a per-type haze,
Now trivial types share a single memcpy song,
And static tables dispatch all day long.
The rabbit tidied the template brigade —
Fewer functions, same tricks, and a cleaner cascade! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main optimization: collapsing trivial-destructor and trivial-copy thunks in the variant implementation to reduce code duplication and binary size.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/3249-variant-trivial-thunks

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/fl/stl/variant.h (1)

334-343: Precondition enforced by all callers — adding a debug assertion is optional.

copy_construct_from() requires a non-empty source (precondition: other._tag != Empty), which is enforced by all callers via if (!other.empty()) guards in the copy constructor (line 136) and copy assignment operator (line 154). The function does not guard internally because the contract is upheld at call sites.

Adding a debug assertion (FL_ASSERT(other._tag != Empty)) would be defensive programming and help catch misuse during development:

Optional: add debug assertion for precondition
     void copy_construct_from(const variant &other) FL_NOEXCEPT {
+        FL_ASSERT(other._tag != Empty);
         FL_DISABLE_WARNING_PUSH
         FL_DISABLE_WARNING(array-bounds)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/stl/variant.h` around lines 334 - 343, Add a debug assertion to the
copy_construct_from method to enforce the precondition that the source variant
is not empty. At the beginning of the copy_construct_from function (right after
the opening brace), add an FL_ASSERT statement that checks other._tag is not
equal to Empty, which will help catch misuse during development and make the
contract explicit within the function itself.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/fl/stl/variant.h`:
- Around line 334-343: Add a debug assertion to the copy_construct_from method
to enforce the precondition that the source variant is not empty. At the
beginning of the copy_construct_from function (right after the opening brace),
add an FL_ASSERT statement that checks other._tag is not equal to Empty, which
will help catch misuse during development and make the contract explicit within
the function itself.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 016fe191-549b-4a55-a681-dd143dd473ed

📥 Commits

Reviewing files that changed from the base of the PR and between d2566be and 00d02de.

📒 Files selected for processing (1)
  • src/fl/stl/variant.h

@zackees
zackees merged commit 6a85aee into master Jun 19, 2026
12 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 19, 2026
@zackees
zackees deleted the feat/3249-variant-trivial-thunks branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant