Skip to content

Optimize branch instructions to short form where branch distance fits in sbyte#529

Draft
Copilot wants to merge 4 commits intomasterfrom
copilot/optimize-branches-to-small-branches
Draft

Optimize branch instructions to short form where branch distance fits in sbyte#529
Copilot wants to merge 4 commits intomasterfrom
copilot/optimize-branches-to-small-branches

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 22, 2026

Branch instructions like Br, Brtrue, Brfalse encode a 4-byte offset by default, but have short-form variants (Br_S, Brtrue_S, Brfalse_S) using a 1-byte signed offset when the target is within ±127 bytes. Previously, a blanket replacement broke large switch statements. This PR adds proper distance-checking before selecting the shorter form.

Changes

General backward-branch optimizer (ILGeneratorTools)

  • Tracks marked label positions in _ilLabelPositions (ConditionalWeakTable<ILGenerator, Dictionary<Label, int>>) — keyed by Label struct directly to avoid any hash collision ambiguity
  • DmarkLabel records il.ILOffset when marking a label
  • Demit(ILGenerator, OpCode, Label) uses TryGetShortFormOpCodeForBackwardBranch to automatically emit short form for backward branches (label already marked) when labelOffset - (ILOffset + 2) fits in [-128, 127]
  • GetShortFormBranchOpCode maps all 13 long-form branch opcodes to their short-form counterparts
  • Clears stale label position data when a pooled ILGenerator is reused (RentPooledOrNewILGenerator), preventing false short-form selection after pool reuse

Specific forward-branch optimizations (always safe, hardcoded)

Patterns where the skipped IL is provably tiny:

Site Change Max skipped bytes
IsFalse unary Brfalse→Brfalse_S, Br→Br_S 3
Reference coalesce with cast Br→Br_S 5 (Castclass)
isLiftedToNull comparison Brfalse→Brfalse_S, Brtrue→Brtrue_S 6
Logical operator labelDone Br→Br_S 1 (Ldc_I4_0/1)

Tests updated

Three existing opcode-assertion tests updated to expect the new short-form opcodes where the optimizer now applies (Issue498, Issue346, Issue159).

Copilot AI linked an issue Apr 22, 2026 that may be closed by this pull request
Copilot AI changed the title [WIP] Optimize branches to small branches Optimize branch instructions to short form where branch distance fits in sbyte Apr 22, 2026
Copilot AI requested a review from dadhi April 22, 2026 07:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize Branches to Small Branches

2 participants