Mikolaj Konarski pushed to branch wip/T27981-ncg-mystery-box at Glasgow Haskell Compiler / GHC Commits: 6c0e3c4c by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 rts: run finalizers soon after the GC that finds them scheduleFinalizers puts the finalizer thread at the end of the run queue, and the thread whose heap overflow caused the GC goes back to its front unless a context switch is pending. So under the RTS timer the finalizers wait for the next context switch, 20 ms by default, and whatever they would free stays live until then: a program that opens and closes handles fast keeps every closed handle's buffers. nofib's maillist, which appends to its output a line at a time, peaks at 16.6 MB of residency where -V0 and -C0, whose scheduler switches whenever another thread is runnable, keep 1.65 MB. Request a context switch when scheduling the finalizers, so that they run at the next block boundary. maillist then keeps 1.65 MB under the default timer and runs 13.1% fewer instructions at -O2, 12.7% at -O1 and 12.7% built at -O0. Across nofib, cacheprof runs 1.4% more at -O2 and 0.87% at -O1, as it does under -V0: run promptly, the finalizers lower the residency (cacheprof's peak 0.82 MB against 0.90 MB), so the major GCs, triggered by the old generation's size against the live data, come more often (cacheprof's 148 against 136 at -O2). Built at -O0, gg runs 0.32% more and treejoin 0.49% fewer; no other program moves by 0.2% beyond its run-to-run noise. Figures of variants not taken were measured on earlier forms of the series. Fixes ISSUE 28060. Assisted-by: Claude Opus 5.5 - - - - - 26775389 by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Address a register offset directly in x86's getAmode getAmode made the mode of CmmRegOff r n by mangleIndexTree r n, building the sum r + n for the alternative of x + lit to take apart. It now gives that alternative's mode, r's register with the offset n, directly, under the same guard, is32BitLit of n at r's width, and where r is not PicBaseReg; the other cases go to the mangled sum as before. The code generated is the same. Measured against its parent: nofib's objects are the same size, as are containers', megaparsec's, vector's and A2T's, and the stage-1 compiler, built by GHC 9.12.4, runs 1.13% fewer instructions compiling T3294 at -O0, 0.45% at -O and 0.44% at -O2; 0.38%, 0.12% and 0.11% fewer compiling T12707; and 0.18% and 0.20% fewer compiling T9961 and T783 at -O0. The stage-2 compiler runs 0.053%, 0.033% and 0.051% fewer compiling nofib's puzzle at -O0, -O1 and -O2, and 0.051% fewer compiling nofib's programs at -O0 and 0.025% and 0.010% fewer at -O1 and -O2, geometric means. The test cmm_regoff loads and stores at q + k for offsets k on both sides of the 32-bit displacement bounds, q passed as p - k so that each access is at a known address. Assisted-by: Claude Opus 5.5 - - - - - c046ebb1 by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Gather a Cmm sum's literals into one constant, and narrow != as == To move into a merge request of its own, together with "Address (i << s) + lit on x86 by a scaled index with no base", "Take the constant out of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset into any sum with a constant", "Assign literals after computed values at the end of a block" and "Drop the assignments that only a discarded assignment read". GHC.Cmm.Opt's special case (a - b) + c ==> a + (c - b) fired whatever b and c were, and where c - b could not fold it put a literal on the left of a subtraction, which x86 cannot encode as an immediate: containers' Set.elemAt, at -O2, computed i + ((-1) - s) for its right step, a mov, a sub and an add where a sub and a dec do. The reassociation (a + b) - c ==> a + (b - c) had the same flaw where b is a literal and c is not, turning (x * y + 1) - w into x * y + (1 - w). This commit gathers such sums into one normal form, which x86's code generator now computes by one LEA or addressing mode (add_int, getAmode); and it narrows != against a literal, as ==, and a comparison of two operands widened alike. cmmMachOpFold now puts an addition or subtraction at one width into the form of Note [Additive normal form] in GHC.Cmm.Opt, its literals summed into one constant: e + k, k - e or e, a difference e - k being left as it is where e has no constant. This takes the place of the reassociations of (a + b) - c and (a - b) + c, and that of (a + b) + c no longer moves a literal c from the top. That reassociation, (a + b) + c ==> a + (b + c) where c is no literal, is master's, and reassocAdd now does it: where a is neither a literal, a register offset nor a MachOp and the folded b + c is a sum at the same width whose right operand is no literal, it builds a + (b + c) as it stands, since cmmMachOpFold would return that sum unchanged, and it folds every other step by cmmMachOpFold, as master's code does. A left-nested sum of n terms still takes n(n-1)/2 steps to become right-nested, as in master's reassociation; each step is now cheaper. The x86 code generator takes the sums left this way into one LEA: add_int computes (a + b) + k as the address of that form and (a - b) + k as (a + k) - b, and getAmode makes a complex addressing mode of (a + b) + k and of (a + (b << s)) + k, and of the same forms less k. Master's clauses below them that take a shift stay, each still reached: x + (y << s) by a sum with no literal, the swap of a shift and a literal by a literal that is no 32-bit displacement, and, where nothing folds, as at -O with -fno-cmm-sink, (x + k) + (y << s) for a register x by array indexing and x + ((y << s) + k) by hand-written Cmm. The narrowing that compares a widened operand with a literal at the operand's width listed MO_Eq but not MO_Ne, so a byte widened to a word was tested with != after a zero extension; MO_Ne is added beside MO_Eq. A comparison of two operands widened alike, from the same width and both by zero extension or both by sign extension, is now done at that width as well, under the literal case's rule for signedness (ISSUE 2080), its tables moved to the top level to serve both. Vector's awshcc and nofib's reverse-complement, lambda and parser gain where != is narrowed like ==, and the boot libraries' comparisons of two operands widened alike, in text, bytestring and ghc-internal's eqWord32, are narrowed too, containers running fewer instructions by them. Gathering a sum's literals can fold a negative constant into a label's offset, as master's own fold of a label less a literal does. AArch64's code generator loaded a label at an offset fitting 12 signed bits by an add whose immediate is unsigned, so an offset such as -8 made its printer panic in check_off; a negative offset now takes the general path, which adds the offset from a register. The tests cmm_fold_lit (Cmm, the reassociations and the narrowing) and cmm_fold_elemAt (Haskell at -O2, Set.elemAt's step) fail without these changes, and cmm_addnf compares each shape over boundary values with the same formula computed in Haskell. Measured against its parent: nofib's programs run 0.22% and 0.21% fewer instructions at -O2 and -O1 and 0.078% fewer at -O0 (geometric means), spectral-norm 11.8% fewer at -O2 and -O1, allocating the same; containers' benchmarks run 0.26% and 0.25% fewer instructions at -O2 and -O1, megaparsec's 0.91% and 0.74% and vector's 0.60% and 0.59%. The stage-1 compiler runs 2.2%, 1.7% and 1.7% fewer instructions compiling MR 16269's CmmDiamondChain at -O0, -O1 and -O2, and at most 0.003% more on any compilation of T3294, T12707, T783 and T9961. Compiling a Cmm procedure that rotates N locals in a loop and returns their sum at -O1, it runs 0.990, 0.971, 0.931 and 0.883 times the instructions at N = 50, 100, 200 and 400. Compiled by the stage-1 compiler, as when building stage 2, GHC.Cmm.Opt allocates 1.98 GB against its parent's 1.24 GB, the cost of addNormalise's own code; at the series' top it allocates 1.83 GB, about half again master's. Assisted-by: Claude Opus 5.5 - - - - - 9e8c17dd by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Address (i << s) + lit on x86 by a scaled index with no base To move into a merge request of its own, together with "Gather a Cmm sum's literals into one constant, and narrow != as ==", "Take the constant out of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset into any sum with a constant", "Assign literals after computed values at the end of a block" and "Drop the assignments that only a discarded assignment read". x86's getAmode took (i << s) + lit, the address of an entry of a closure table, which tagToEnum# and a derived Enum's toEnum, succ and pred load, by its default branch: the shift computed into a register, which became the base, and lit the displacement, as shlq $3,%rax then movq tbl(%rax),%rbx. Its clause for x + lit, which takes every literal a displacement holds (is32BitLit), now takes such an x, s at most 3, as an index scaled by 2^s with no base register and lit the displacement, movq tbl(,%rax,8),%rbx, with the default branch's relocation. add_int takes the value (x << s) + k into the same LEA. The clause turning (a << n) + lit around stays, for the literals x + lit does not take: a label on Windows (Note [%rip-relative addressing on x86-64]) and an integer or a label's offset wider than 32 bits; its comment says so. Under -fPIC and -dynamic a table's label reaches getAmode as PicBaseReg plus the label or as a load from the GOT, except on Windows, where it is a literal that x + lit does not take, so those loads are unchanged. Measured against its parent: nofib's programs run 0.031%, 0.029% and 0.19% fewer instructions at -O2, -O1 and -O0 (geometric means), at -O2 CSD 0.52% fewer, cryptarithm2 0.49%, ansi 0.42%, puzzle 0.35% and cichelli 0.32%, none more by 0.2%, the geometric means of their allocation unchanged; containers' benchmarks run 0.011% fewer at -O2 and -O1, IntSet's eq 1.1% and spanAntitone of IntSet and IntMap 1.0% fewer, and vector's 0.090% and 0.084% fewer, findIndexR 1.7% and 1.6%; megaparsec's geometric means fall by 0.035% and 0.038% and A2T's sample runs 0.004% fewer, none of their benchmarks rising. The stage-1 compiler runs at most 0.004% more instructions compiling T3294, T12707, T783, T9961 and ManyBasicBlocks, and its allocation moves by 0.001% or less. The test cmm_scaledlit loads and stores at (i << s) + lbl for s from 0 to 3 and lbl plus or minus 8, and computes (x << s) + k at 64, 32, 16 and 8 bits for s from 0 to 4, with k small or at a bound of 32 bits or of a narrower width, and at 64 bits past the 32-bit bounds, comparing each with the same formula computed in Haskell; ClosureTblAmode checks that tagToEnum#'s closure table is addressed with no base register, and is skipped on Windows and where code is position-independent by default. Assisted-by: Claude Opus 5.5 - - - - - b7ef204f by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Take the constant out of a shifted or scaled sum in Cmm's sums To move into a merge request of its own, together with "Gather a Cmm sum's literals into one constant, and narrow != as ==", "Address (i << s) + lit on x86 by a scaled index with no base", "Fold cmmOffset's offset into any sum with a constant", "Assign literals after computed values at the end of a block" and "Drop the assignments that only a discarded assignment read". The additive normal form (Note [Additive normal form] in GHC.Cmm.Opt) gathered the constants of an addition's operands only where an operand was a sum, a difference, a register offset or a literal, so p + ((i + 1) << 3), the element after i of an array, kept its constant inside the shift, and x86 computed i + 1 and the shift before loading. addView now views an operand (e + k) << s or (e + k) * c at width w, k an integer and s < w, as the term e << s or e * c with the constant k << s or k * c, the product distributing over the sum modulo 2^w, where that constant narrowed to w fits in 32 bits; the old view is sumView. p + ((i + 1) << 3) becomes (p + (i << 3)) + 8, one address of x86's getAmode, and the closure table entry ((t - 1) << 3) + lbl becomes (t << 3) + (lbl - 8), with one label literal. Left as they are: (k - e) << s, whose term e << s would be subtracted, which no x86 address does, while p + ((1 - j) << 3) + 24, an element of an array in nofib's fem, gamteb and puzzle, is one address; and a constant wider than 32 bits, which x86 would move into a register where k cost nothing, as in (x + 1) << 40. Measured against its parent: nofib's CSD runs 0.78% and scs 0.22% fewer instructions at -O2 and -O1, and built at -O0 dom-lt, n-body, kahan and fannkuch-redux run 0.60% to 0.69% fewer and others by less, no program more by 0.2%, the geometric means 0.014%, 0.012% and 0.066% lower at -O2, -O1 and -O0; vector's benchmarks run 0.12% fewer at -O2 and -O1, nextPermutation and prevPermutation of a small vector 1.8%, and A2T's sample 0.016% fewer, none of its cells more by 0.2%; containers' and megaparsec's geometric means move by 0.009% or less; allocation is unchanged in the packages' benchmarks and moves by less than 0.2% in nofib's programs and A2T's cells. The stage-1 compiler's instructions and allocation compiling T3294, T12707, T783, T9961 and ManyBasicBlocks change by 0.034% or less, and the stage-2 compiler allocates 0.052%, 0.061% and 0.12% less compiling nofib's programs at -O2, -O1 and -O0 (geometric means). Compiled by the stage-1 compiler, as when building stage 2, GHC.Cmm.Opt allocates 9.8% more (2.18 against 1.98 GB), addNormalise's growth by this view. The test cmm_fold_scaled checks in the Cmm dump p + ((i + 1) << 3), q + (i + 2) * 24 and the two shapes left as they are, and cmm_addnf now also computes such shifts and products as operands of additions and subtractions, and loads at them, comparing each with the same formula computed in Haskell. Assisted-by: Claude Opus 5.5 - - - - - 3a32d310 by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Fold cmmOffset's offset into any sum with a constant To move into a merge request of its own, together with "Gather a Cmm sum's literals into one constant, and narrow != as ==", "Address (i << s) + lit on x86 by a scaled index with no base", "Take the constant out of a shifted or scaled sum in Cmm's sums", "Assign literals after computed values at the end of a block" and "Drop the assignments that only a discarded assignment read". cmmOffset summed its offset into a MachOp only of the form e + k and wrapped any other MachOp in a new addition, folding nothing. Sink's inl_exp inlines a local's value into a register offset l + n by cmmOffset, so that (e - 1) + 1 was left as it is: with Sink on, the NCG never folds, ncgDoConstantFolding being not (gopt Opt_CoreConstantFolding dflags || gopt Opt_CmmSink dflags). cmmOffset now reads a MachOp through the additive normal form's own view, addView, moved with sumView and their types from GHC.Cmm.Opt to GHC.Cmm.Utils, and adds the offset to the constant of e + k, e - k and k - e alike: a sum whose constant cancels becomes its term, a register plus a constant a register offset. Every caller gets it, the NCG's jump-table index among them. cmmOffset reads the view only of an addition or a subtraction, never of the shift or product that addView takes apart, so a local (e + k) << s inlined into an offset stays ((e + k) << s) + n, as before. At -O1 and -O2 a derived Enum's succ and pred each lose one instruction, in nofib's puzzle and ben-raytrace and in ansi-terminal-types, and dataToTag# x plus or minus a literal loses one; every other object of nofib's programs at -O0, -O1 and -O2, of containers', megaparsec's and vector's benchmarks at -O1 and -O2 and of their dependencies stays the same size, and the instruction counts of puzzle and ben-raytrace move by 0.0002% or less. The stage-1 compiler's instructions and allocation compiling T3294, T12707, T783, T9961 and ManyBasicBlocks change by 0.032% or less, and the stage-2 compiler allocates 0.053%, 0.062% and 0.12% more compiling nofib's programs at -O2, -O1 and -O0 (geometric means): at -O0 real/eff/S 0.33% more, and VSD, CSD, scc, rfib, tak and others 0.20% to 0.28% more, the parent having taken 0.20% to 0.26% off the same programs; at -O1 and -O2 S, VSD and CSD 0.19% to 0.26% more. Compiled by the stage-1 compiler, as when building stage 2, GHC.Cmm.Utils allocates 42% more (1.04 against 0.73 GB), sumView inlined into addView, and GHC.Cmm.Opt 12% less (1.91 against 2.18 GB); at the series' top Utils allocates 1.01 GB, about two fifths again master's. The test cmm_sinkoff sinks such values into an offset at 64, 32 and 8 bits, its constants at the wrap boundaries, and compares each with the same formula computed in Haskell; cmm_swoff switches on e - k and k - e at 64 and 32 bits over jump tables whose range starts at 100. EnumTagOffset greps the assembly of a constructor's index plus 3 and minus 1, and of the next and the previous constructor loaded from its closure table: the - 1 that takes the index from the pointer's tag folds into the literal and into the table's displacement, where the parent commit's compiler subtracts it by an instruction of its own in each of the four. Assisted-by: Claude Opus 5.5 - - - - - ded57a76 by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Predict an inequality with a literal in static branch prediction ohPredicts, static branch prediction's opcode heuristic, predicts that a comparison with a literal is unlikely to come out equal, but it matched only MO_Eq. The control-flow optimisation turns an equality into an inequality where that lets the test's true side fall through (Note [Invert Cmm conditionals] in GHC.Cmm.ContFlowOpt), and so spelt the same test went unpredicted, its two sides weighted alike. ohPredicts now predicts the true side of an inequality with a literal (0.7), as it predicts the false side of an equality, except where an operand is masked by MO_And, as in a pointer tag test, (x & 7) != 0, or a test of a bitmap's bits, or is a constructor tag: one read from an info table, an unboxed sum's, or a local register every assignment to which is a tag, which a pass over the procedure's Cmm finds. Whether those bits are set, or which constructor a tag names, depends on the type or the data, which the CFG does not record, so a test of a constructor tag is predicted as before (Note [Static prediction of tag tests]). Predicting every inequality made containers' benchmarks take up to 3.1% more instructions, through the tag tests of tree lookups; leaving out only pointer tag tests, intmap fromSet took 1.3% to 1.8% more, through buildTree's bitmap test. What this removes is a tie. In megaparsec's sepEndBy loop, a cold continuation's edge into the loop's second head weighs as much as the hot edge into it once "Hand calcFreqs a procedure's loops inner first" estimates them, because the test before them, written as != 0, is estimated 50/50; the tie gives the cold block the fall-through, and every element a jump. With this commit the hot edge is the heavier one. The trade is k-nucleotide's hash table lookup: the exits of its bucket loop, written as tests for zero, come out as != 0 and are now predicted to stay in the loop, so that with the loop-exit heuristic the loop's back edge outweighs its entry; block layout gives the back edge the head's fall-through, and every first probe, which finds its key about 95% of the time, pays a jump. The commit that lets a loop's back edge outrank its entry makes this layout anyway. The gains include containers' intmap compareSize:n (3.4% fewer instructions) and nubOrd issue1202_repeat (0.89% fewer at -O1), and megaparsec's endBy (0.63% to 0.64% fewer at -O2). TODO: the exception goes by an operand's form, not by what decides the test: a parity test, its mask inside arithmetic, is predicted, and an evaluation test, (x & 7) != 0, is left out with the constructor-tag tests; predicting evaluation tests as evaluated, in either spelling, cost nofib 0.36% more instructions, and leaving parity tests out is still to be measured. Measured against the parent commit, in instructions: nofib's programs move by less than 0.01% at every level, k-nucleotide taking 0.49% more at -O2 and 0.26% at -O1; containers' benchmarks move by less than 0.01% at both levels, the compareSize:2 rows of intmap and intset and intset's deleteMax taking one instruction a call more; megaparsec's take 0.03% fewer at -O2 and 0.02% at -O1; vector's move by less than 0.01%; in orthotope's A2T benchmark maximumA.one over small strided arrays takes two instructions a call more (0.4% to 0.6%), and many of its cells take 0.2% to 0.4% fewer, both by one jump in absAxesAndStartT: of the two return blocks that run back into the tag test at its head, the layout now places before the test the one most cells take, and maximumA.one's strided cells take the other. No benchmark's allocation moves by 0.05%; the compiler allocates at most 0.026% more compiling perf/compiler's T3294, T12707, T783 and T9961. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - d69163ad by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Find a CFG's back edges by one depth-first search findBackEdges classified every edge of the CFG (classifyEdges, which timestamps the visits of a depth-first search from the entry) to find the few that lead back to a block on the search's path. optHsPatterns calls it on every procedure, at every optimisation level, to give back edges their bonus. findBackEdges is now that depth-first search itself: it visits the successors in the same order and collects, as it goes, the edges into a block still on its stack, leaving out an edge from a block to itself, which classifyEdges calls a self loop rather than a back edge. classifyEdges and its EdgeType, in GHC.Data.Graph.Directed, had no other user and are gone. The generated code is the same: the assembly of perf/compiler's T3294, T12707, T783 and T9961 at -O0 and -O, and the object code of nofib's programs at -O2, are the parent's. The compiler allocates 0.2% less compiling T3294 at -O0, 0.7% less compiling T12707, 1.0% less compiling T783 and 1.0% less compiling T9961; at -O, 0.3% less compiling T12707 and 0.2% less compiling T783; and compiling nofib's programs at -O2, 0.20% less in geometric mean and up to 0.36% less (spectral/clausify). Compiling MR 16269's CmmDiamondChain at -O1 and -O2, the compiler allocates 0.19% less. Assisted-by: Claude Opus 5.5 - - - - - 00ac2ccc by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Drop jumps over blocks dropJumps empties dropJumps removes a block's last jump where it can fall through to the next block, and a jump-only block it so empties stays as a label, so that a jump over it to the block after is left as a jump to the next instruction (x86-64's eb 00, which master's intmap benchmarks at -O1 carry). It now looks past the blocks that are empty or that it leaves empty, by a fold from the end over the blocks it has already processed, among which a block it leaves empty is empty already. Looking ahead over the blocks still to process instead, as first written, took time exponential in a run of blocks holding one jump each; the fold builds the whole list before returning its first block, and the compiler allocates 0.081% more compiling perf/compiler's T783 at -O0 than with that look-ahead. Measured against its parent: built at -O1, containers' intset folds over sparse sets run 1.6% (foldr_elem) and 0.90% (foldl_elem) fewer instructions and intmap's fromSetA 0.49% to 1.4% fewer, the geometric mean 0.006% lower, and no benchmark rises; at -O2 containers' benchmarks neither rise nor fall. nofib's programs move by less than 0.2% at every level, and their geometric means, megaparsec's and vector's by 0.001% or less; no cell of A2T's sample moves by 0.2%. The assembly of T3294, T12707, T783, T9961 and ManyBasicBlocks is the parent's, and the compiler runs at most 0.086% more instructions compiling them (T783 at -O0) and allocates up to 0.018% less. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 05cdacb8 by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Let a loop's back edge outrank its entry in block layout sequenceChain lays the blocks out by fusing chains along the heaviest edges first, by the final edge weights. Under -fcmm-static-pred, on at -O1 and -O2, those are the frequencies static prediction estimates, which can rate a loop's back edge below its entry: where the branch that decides whether the loop goes on has no back edge among its targets, the other heuristics predict it, and they can predict staying in the loop to be unlikely, as in a lookup down a tree (Note [Static prediction of tag tests]). The entry then falls through into the loop's head, and every iteration pays a jump back. optHsPatterns gives back edges a bonus (increaseBackEdgeWeight), but static prediction replaces the weights of the branches its heuristics cover with its predictions, so that the bonus counts only at those it leaves alone, a heap or stack check's and those whose targets are all back edges. sequenceChain now raises (preferBackEdges) each back edge by a little more than the weight of the heaviest edge into its head that is not a call, a back edge or a self loop, which keeps the order of several back edges into one head; Note [Layout relevant edge weights]. A back edge out of a jump table is not raised: it cannot fall through, so raising it would only take the head's fall-through from an edge that can. Nor is a back edge out of a block with another successor: that block executes its branch whichever successor falls through, so falling through saves nothing an iteration, while every entry pays a jump; leaving such edges out takes 1.55% off intset folds:sparse foldr_elem and 0.78% off foldl_elem, and 6.4% off folds:dense foldl'_maximum, at -O2. preferBackEdges takes the back edges from findBackEdges, now exported. The garbage collector's return to the block that made a heap or stack check is no such loop: a back edge leaving a block that follows a failed check stays as it is. checkFailures, in GHC.CmmToAsm.CFG, finds those blocks: the targets of the less likely edges of a branch that getCfg tags HeapStackCheck, one whose condition reads SpLim, HpLim or BaseReg, and their successors, such as the block the garbage collector returns to, which can be a continuation that a call returns to as well. A block that follows such a block and whose one out-edge has the code generator as its source, such as a block the register allocator puts there, counts as following a failed check too (coldBlocks). Raising those back edges too makes containers' benchmarks take 0.28% more instructions (set fromAscList:fusion 3.2%, intset fromList:worstCase 3.0%); leaving out the blocks that follow a failed check but not the block the register allocator puts after such a block, 0.09% more (map alter insert 0.9%). A new Note, [Frequencies before register allocation] in GHC.CmmToAsm.CFG, names two shapes coldBlocks misses: the block allocMoreStack splits off a block the garbage collector returns to, and a fixup block on a failure edge, which takes the edge's tag. A TODO at coldBlocks points there. Building the set in GHC.CmmToAsm instead, from checkFailures' blocks, the blocks allocMoreStack splits off a cold entry block and the fixup blocks on an edge out of or into a cold block, changed a few procedures' layout in nofib and moved no figure measured, while costing up to 0.03% more compile allocation at -O0. Nor is a back edge into the one successor of the procedure's entry block raised: the entry would then jump to that block at every call, which a loop that seldom iterates does not win back. The RTS's entry code has such loops, which retry on an indirection: raising their back edges made stg_BLACKHOLE_info, stg_enter_info and stg_forceIO_info begin with a jump into the loop, so that stg_BLACKHOLE_info ran an instruction more for every blackhole entered. Where the code generator split the entry block, as allocMoreStack does, and the block holding the rest of its code has one successor, that successor stands in for the entry's. Measured against the parent commit, in instructions; sequenceChain runs only under -fblock-layout-cfg, on at -O1 and -O2. At -O2 nofib's programs take 0.051% fewer (queens 1.2%, wheel-sieve1 1.0%, banner 0.47%), vector's benchmarks 0.40% fewer (leaffix 3.4%, rootfix 2.7%, listRank 2.2%), containers' 0.094% fewer and megaparsec's 0.060% fewer (reachOffsetNoLine 0.78%, reachOffset 0.46% to 0.60%); at -O1 nofib's take 0.048% fewer (knights 1.3%, wheel-sieve1 0.99%, banner 0.46%); fannkuch-redux moves by no more than its noise. Some of containers' and megaparsec's benchmarks rise; the rises are trades. The rule's own is the jump a loop's entry now pays, which its iterations seldom win back: intmap lookup_mixed 2.0%, whose lookups gain nothing from the descent that now falls through, and intset's intersection and difference benchmarks, 0.4% to 0.8%: the continuation that evaluates the second set now jumps into differenceTip's descent, a loop whose head has two back edges and which runs no iteration where that set is a Tip, as in these benchmarks, while IntMap's lookups, of the same shape, iterate about sixteen times an entry and gain 2.5% to 3.0%; no static rule tells the two apart. containers' restrictKeys, withoutKeys and graphFromEdges n=15, and megaparsec's hexadecimal, decimal and octal at -O1, pay the same jump, and so does megaparsec's scientific.4000, which calls decimal's decimal_: 20 instructions more, as decimal.4000. The fused rows, containers' map fromDistinctDescList:fusion, map and set fromList-distinctAsc:fusion, and map fromListWith-asc:fusion and fromListWithKey-asc:fusion, take 0.4% to 0.8% more at -O2, and set fromDistinctDescList:fusion 0.90% more. Raising back edges only into heads outside every enclosing loop reverts them, and with them nubInt's noFusion_repeat, which pays the same jump into IntSet's member, 1000 instructions a run, and issue1202_repeat, intmap lookup_mixed and intset alterF:delete:present; but it gives back the gains of intmap lookup_hits, lookup_most and index (2.9% to 3.0%), lookup_misses (2.5%), intset member and alterF:member (1.0% to 1.1%), and vector's listRank (2.2%) and awshcc (1.8%), at -O2. Where two back edges raised alike into one head tie, the static order breaks the tie: at -O1 megaparsec's reachOffset pays 78000 instructions a call, isWideChar's loop head having two back edges, tied, and the tie going by label order to the one that ASCII input never takes. Flipping the order takes 4.0% off intmap lookup_half, 2.0% off lookup_mixed and 1.2% off intset alterF:delete:present, and at -O1 1.1% off megaparsec's reachOffsetNoLine and 0.8% off errorBundlePretty, but adds 2.5% to nofib's fasta at -O2 and 1.2% at -O1, gives back 96% of banner's gain, and adds 5.9% to intset fromAscList:fusion, 2.3% to fromAscList, 1.3% to mapMonotonic and, at -O1, 0.9% to vector's next and prevPermutationBijective; the static order is kept. No benchmark's allocation changes beyond nofib's run-to-run noise. The compiler allocates 0.10% and 0.13% more compiling perf/compiler's T12707 and T783 at -O and 0.22% more compiling MR 16269's CmmDiamondChain at -O1 and -O2; elsewhere its allocation moves by less than 0.1%. The stage-2 compiler allocates 0.24% and 0.23% more compiling nofib's reptile and puzzle at -O2. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.BlockLayout allocates 16% more (1.10 against 0.95 GB). Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 870b4739 by Mikolaj Konarski at 2026-11-13T19:46:55+01:00 Hand calcFreqs a procedure's loops inner first calcFreqs estimates block frequencies by Wu and Larus's algorithm, which takes the loops from inner to outer, as its comment says: an enclosing loop's frequencies use the cycle probability of each loop inside it, computed when that loop is processed. mkGlobalWeights handed it the loops in loopInfo's order, by back edge in the order of the CFG's labels, so an enclosing loop could come first. calcFreqs then took the probability of an inner loop's back edge itself, often 1.0, for that loop's cycle probability, which calcFreqs caps at 1 - 1/512, so the inner loop's head counted up to 512 times as often as it was entered. The cycle a heap check makes through the garbage collector is such an inner loop in any loop that allocates: in containers' map benchmarks, the head of the loop that looks keys up was estimated to run several times as often as the edges into it. mkGlobalWeights now sorts the loops by the size of their bodies, an inner loop's body being a proper subset of an enclosing one's. This makes block layout lean on the estimate more. Taking a procedure's loops in label order could make a head's frequency up to 512 times its inflow, so that the loop's back edge won by accident; where static prediction calls staying in a loop over a tree unlikely (Note [Static prediction of tag tests]), it is now the rule that a back edge outranks the loop's entry ("Let a loop's back edge outrank its entry in block layout") that keeps layout from following the estimate. Measured against the parent commit, in instructions; calcFreqs changes the generated code only under -fcmm-static-pred, on at -O1 and -O2. No nofib program moves by 0.2%, no benchmark of containers or megaparsec rises at -O2, and vector's benchmarks take 0.037% fewer at -O2 (findIndexR_manual 1.07% fewer) and fannkuch-redux 0.19% fewer. No benchmark's allocation changes beyond nofib's run-to-run noise. The compiler's allocation compiling perf/compiler's T3294, T12707, T783 and T9961 moves by less than 0.1%. Assisted-by: Claude Opus 5.5 - - - - - 41710a15 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Count self loops as loops in static branch prediction loopInfo took an edge for a back edge where its target dominates its source, by mkDomMap's sets, which hold a block's own label only where the block is a leaf of the dominator tree. So a self loop counted as a back edge only from a leaf, and the retry of an atomic operation that x86 emulates with a compare-and-swap loop (cmpxchg_code), whose block dominates the block after it, counted as none: calcFreqs then took that block for irreducible and gave frequency 0 to it, to every block it dominates and to their edges, a surrounding loop's back edge among them. mkDomMap's sets now hold each block's own label but the root's, so that a self loop counts as a back edge but at the root, which no edge enters as a back edge. mkDomMap also builds the map in one fold over the dominator tree, inserting each block but the root as it walks the tree, where it built a list of pairs, each block with its dominators, and made a map of the list. The fold is taken from Simon Jakobi's MR 16269, for ISSUE 27448, which also changes what the sets hold. This fixes ISSUE 28093, self loops missed as back edges, as MR 16269 does. The retry edge cmpxchg_code adds now has a TransitionSource of its own, AsmCodeGenRetry, which staticBranchPrediction leaves out of its rule that a back edge is more likely than any other edge, so that the retry is predicted to be rare rather than to repeat seven times in eight. Note [Static Branch Prediction] says so. Andreas Klebinger's MR 16535 overlaps with this commit at that edge: it builds that loop's edges by continueInNewBlock and addColdSelfLoop, and the two changes conflict there. The back edges staticBranchPrediction tests were a Set of pairs, master's, looked up for each successor of each block; they are now a LabelMap from each block to the LabelSet of the blocks its back edges enter, looked up once a block. Measured against the parent commit, on x86-64: the assembly of perf/compiler's T3294, T12707, T783 and T9961 at -O0 and -O is the same, and so are the objects of nofib's programs at -O2; of containers' objects only graph-benchmarks' Main changes, and no benchmark of containers, vector or megaparsec moves beyond its noise. The stage-1 compiler allocates at -O 5.5% less compiling perf/compiler's T783, 0.35% less compiling T12707, 0.25% less compiling T3294 and 0.018% less compiling T9961, and 27.5% less compiling MR 16269's CmmDiamondChain at -O1 and -O2. Most of the saving is the fold's, at T783 and CmmDiamondChain. At -O0, where static prediction is off, the allocation moves by 0.014% or less. Assisted-by: Claude Opus 5.5 - - - - - 4d261894 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Specialise the linear allocator and liveness pass to x86-64 The linear allocator is overloaded in the instructions and in the free registers, and the liveness pass in the instructions, so on x86-64 too they called every instruction method through a dictionary: the code generator is specialised for each target, but its calls of regAlloc and cmmTopLiveness went to the overloaded functions. Both now have a SPECIALISE pragma for x86's instructions, and NOINLINE [0], without which neither rule fires, when the boot compiler builds stage 1 or when the stage-1 compiler builds stage 2: cast worker/wrapper makes each function an alias of its body, cast to UniqDSM, and the alias inlines from the function's own phase whatever its rules' phase, so it inlines into the code generator before the call there becomes one at x86's instructions, which is what the rule rewrites. A phase on the SPECIALISE pragmas alone, [0] or [2], makes neither rule fire. linearRegAlloc passes the other targets' free registers through a NOINLINE function, which the specialiser does not specialise, so that only x86-64's get a copy of the allocator; Note [Specialising the linear allocator]. The allocator's constraint synonym no longer requires Outputable free registers, which nothing prints, and is renamed from OutputableRegConstraint to RegAllocConstraint. Liveness.hs now imports GHC.CmmToAsm.X86 for its Instruction instance, which Linear.hs, importing Liveness.hs, has as well, so the allocator's modules that import either compile after the x86 code generator; this makes no import cycle, as of the allocator's modules the x86 code generator imports only GHC.CmmToAsm.Reg.Target. Specialising joinToTargets as well, with NOINLINE [0], saved the compiler less allocation than this commit does. The idea of specialising the allocator comes from the draft MR 4764 by Ben Gamari and Andreas Klebinger, which overlaps with this commit: MR 4764 specialises the linear allocator to x86-64 and i386, by INLINEABLE pragmas on the allocator's functions and SPECIALIZE pragmas in GHC.CmmToAsm.X86, and this commit specialises it and the liveness pass to x86-64, by the SPECIALISE pragmas above. The generated code is the same: nofib's object files are the parent's size. The stage-1 compiler allocates 1.7% less compiling perf/compiler's T3294 at -O0 and 0.65% less at -O, 1.2% less compiling T12707 at -O0 and 0.40% less at -O, 0.99% less compiling T783 at -O0 and 0.19% less at -O, and 1.6% less compiling T9961 at -O0, though only 0.001% less at -O, where CI compiles it. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.55% less. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear allocates 65% more (2.57 against 1.56 GB) and GHC.CmmToAsm.Reg.Liveness 31% more (2.15 against 1.64 GB). The compiler's code grows by about 100 KB. The series' figures for its pragmas, these among them, come from stage-1 compilers built by GHC 9.12.4; at the series' top a stage-2 compiler with the series' pragmas, against one without them, keeps every sign: compiling T3294, T783, T12707 and T9961 at -O0, -O and -O2 and MR 16269's CmmDiamondChain and nofib's puzzle at -O0, -O1 and -O2, it runs 0.032% to 4.7% fewer instructions and allocates 0.038% to 4.1% less. Figures that the per-commit measurements do not cover were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 245471aa by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Record the linear allocator's spills only for -ddump-asm-stats recordSpill kept every spill and reload the linear allocator inserts, with its reason, in ra_spills, for the statistics -ddump-asm-stats prints, their only reader. It now keeps them only when that flag is on. The comments in GHC.CmmToAsm.Reg.Linear.Base that called the flag -ddrop-asm-stats now call it -ddump-asm-stats. The statistics printed are the same, and so is the generated code. The stage-1 compiler allocates 0.20% less compiling perf/compiler's T3294 at -O0. Compiled by it, as when building stage 2, GHC.CmmToAsm.Reg.Linear.JoinToTargets allocates 19% more (0.53 against 0.45 GB). Assisted-by: Claude Opus 5.5 - - - - - 062ef52a by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Check the order of liveness SCCs where jump targets are looked up computeLiveness checked that a procedure's SCCs come in reverse dependency order (checkIsReverseDependent) in a walk of its own, gathering every instruction's jump destinations, and panicked otherwise. The liveness pass looks every jump target's live-in registers up anyway, taking none for a target missing from its map; that lookup now panics instead, naming the target. For this, livenessSCCs enters the blocks of a cyclic SCC in the map before the SCC's first walk, with no register live, which is what the lookup took them to have, so that a target can be missing only where the SCCs are out of order, or where the CFG that gave the reachable blocks (sccBlocks) lacks it. The separate walk goes, and with it computeLiveness, which then only called livenessSCCs: regLiveness calls that itself. The generated code is the same. The stage-1 compiler allocates 0.61% less compiling perf/compiler's T3294 at -O0 and 0.24% less at -O, 0.55% less compiling T12707 at -O0 and 0.21% less at -O, 0.66% less compiling T783 at -O0 and 0.15% less at -O, and 0.68% less compiling T9961 at -O0. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.13% less. Assisted-by: Claude Opus 5.5 - - - - - 10de9388 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Keep a procedure's imports only where they are emitted cmmNativeGens forced the imported symbols of each procedure, rendered as text, to avoid a space leak, and kept them for makeImportsDoc, which emits them only where needImportedSymbols holds; on x86-64 Linux that takes -dynamic -fno-PIC. Where needImportedSymbols does not hold, cmmNativeGens now neither forces nor keeps them. The generated code is the same, also under -dynamic, -fPIC and -dynamic -fno-PIC. The stage-1 compiler allocates 0.13% less compiling perf/compiler's T9961 at -O0. Assisted-by: Claude Opus 5.5 - - - - - 7df287a5 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Copy no register list in x86's mkRU where every register counts regUsageOfInstr on x86 and x86-64 filtered both of an instruction's register lists, keeping the virtual registers and the real ones an allocator may hand out (interesting), and so copied both lists for every instruction. mkRU now returns a list unchanged where every register in it is kept. Sylvain Henry's MR 16843 (ISSUE 28008) overlaps with this commit: MR 16843's register usage DSL tests each register as it adds it, but copies a list of registers it is given as it tests them, where this commit returns such a list unchanged when every register in it is kept. The generated code is the same. The stage-1 compiler allocates 1.2% less compiling perf/compiler's T3294 at -O0 and 0.45% less at -O, 0.75% less compiling T12707 at -O0 and 0.24% less at -O, 0.52% less compiling T783 at -O0, and 1.5% less compiling T9961 at -O0. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 3.3% less. Assisted-by: Claude Opus 5.5 - - - - - fbaafd73 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Mark the registers an instruction clobbers allocated, free or not clobberRegs marked allocated those of the registers an instruction clobbers that were free, listing the free registers of every class for each instruction that writes a real register, with its own copy of allFreeRegs from GHC.CmmToAsm.Reg.Linear.FreeRegs, and looking each clobbered register up in the list. The FR class now has frClobberRegs, which marks the clobbered registers allocated: by default those of them that are free, by allFreeRegs, as clobberRegs did, since on AArch64, RISC-V and LoongArch allocateReg panics on a register already allocated; on x86-64, whose allocateReg marks a register that is not free as it marks a free one, it marks every one of them, listing nothing. clobberRegs calls it, and GHC.CmmToAsm.Reg.Linear no longer imports the register class modules that only the copy used. The free registers after a clobber are the same on every target, and so is the generated code on x86-64. The stage-1 compiler allocates 0.095% less compiling perf/compiler's T3294 at -O0, 0.41% less compiling T12707, 0.47% less compiling T783, and 1.2% less compiling T9961; at -O, 0.13% less compiling T12707. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.49% less. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear.FreeRegs allocates 87% more (0.50 against 0.27 GB). Assisted-by: Claude Opus 5.5 - - - - - 5af137b7 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Keep an instruction's register usage in its liveness The liveness pass's backward walk computes the register usage of every instruction it annotates (regUsageOfInstr), and its forward walk (livenessForward), the linear allocator's genRaInsn and the graph allocator's spill cost (slurpSpillCostInfo) and spiller (regSpill_instr) computed it again. Liveness now keeps it (liveUsage), and those use the kept usage instead. patchRegsLiveInstr, which only the graph allocator reaches, computes the patched instruction's usage again, as an instruction's usage can depend on whether its registers are equal: x86's VXOR of a register with itself into itself reads nothing. A new Note in GHC.CmmToAsm.X86.Instr, [What x86's regUsageOfInstr reports], lists that case with the others where the usage is not what the processor does. This commit overlaps with Sylvain Henry's MR 16843 (ISSUE 28008), which keeps the usage in the liveness annotation too and also builds it more cheaply in every backend, but has neither that Note nor the two changes to genRaInsn below; MR 16843 was read before this commit was written. genRaInsn also takes the list of the virtual registers an instruction reads as it is built when the list holds at most two registers, distinct; master passed every such list through nubOrdOn to remove repeats. It also patches an instruction's registers without master's patch_map, a UniqFM that listToUFM built for every instruction from the virtual registers the instruction reads and writes, paired with the real registers allocated to them: patchLookup takes, by unique, the register of the last written pair whose vreg is the one it is given, or else of the last read one, the entry listToUFM kept. The generated code is the same, with the linear allocator and with -fregs-graph. The stage-1 compiler allocates 3.7% less compiling perf/compiler's T3294 at -O0 and 1.4% less at -O, 1.8% less compiling T12707 at -O0 and 0.54% less at -O, 1.3% less compiling T783 at -O0, and 2.3% less compiling T9961 at -O0. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.34% less. Assisted-by: Claude Opus 5.5 - - - - - 478aa8b4 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Walk a block of a cyclic SCC again only when its successors change livenessSCCs annotated the blocks of a cyclic SCC by walking all of them again until the registers live on entry to every block stopped changing, comparing two whole block maps as lists after each round. livenessCyclic now walks a block again only when the registers live on entry to one of its successors in the SCC, or their formats, have changed since its last walk. The old loop compared only which registers are live (the Eq of Regs ignored formats), so it could stop before a wider format had reached every block of the SCC, the case Note [Register formats in liveness analysis] describes; the new one carries formats through as well, and Regs' Eq now compares them too. This fixes ISSUE 27619 and does what ISSUE 27437 asks: the walk itself finds the changes, and no whole block map is compared. Two vector formats of a register are now compared by width where the liveness join keeps the wider (compareFormats) and where a write kills a vector value no wider than the format written. This commit overlaps with Simon Jakobi's MR 16537, which fixes both issues by iterating the fixpoint over the SCC's blocks until the formats of the registers live on entry converge, and also removes the derived Ord of formats, comparing them by width: this commit follows it in carrying the formats through and in comparing vector formats by width, walks again only the blocks whose successors changed where MR 16537 walks every block of the SCC each round, and takes its regression test T27619 unchanged. The liveness join keeps the wider of two vector formats of a register: compareFormats, in GHC.CmmToAsm.Reg.Regs, compares two vector formats by width, and two vectors of one width, as every other pair, by Format's derived Ord, so that the order stays total. minusCoveredRegs lets a write kill a vector value no wider than the format written, and shrinkingRegs, which nothing calls, compares by width likewise. The derived Ord, which ISSUE 27619 also notes, ranks a vector by its number of elements before their format: by it, the join could keep a register read at two vector formats at the narrower, and a write at the narrower kill a value live at the wider, cases no x86 input was found to reach, and a write killed no value live at a format of its width ranked above its own. The new unit test testFormatWidths, in regalloc_unit_tests, checks the join both ways and the kill between formats of different widths and of one; it fails without the width comparison. The generated code is the same on every program measured outside SIMD code. Of perf/compiler's T3294, T12707, T783 and T9961, only T9961 at -O has a cyclic SCC, and the stage-1 compiler's allocation compiling it moves by 0.034%; compiling nofib's programs at -O2, the stage-2 compiler allocates 0.17% less in geometric mean and up to 3.9% less (spectral/puzzle). Compiling MR 16269's CmmDiamondChain at -O1 and -O2, the stage-1 compiler allocates 31.5% less. Compiled by it, as when building stage 2, GHC.CmmToAsm.Reg.Liveness allocates 24% more (2.42 against 1.95 GB). In SIMD code, of the testsuite's simd tests compiled at -O1 and -O2, with and without -mavx2, int32x4_basic and word32x4_basic, with and without _baseline, lose one register move without -mavx2 to the width comparison: SSE2's Int32X4 insertion writes at VecFormat 4 FmtInt32 registers it reads at VecFormat 4 FmtFloat, so that by the derived Ord the write killed nothing and those registers were live into the procedure. int8x16_arith and word8x16_arith change one symbol's name only, and every other test that compiles gives the same code, as nofib's multiplier, primes, puzzle and para do. Compiling perf/compiler's T3294, T783, T12707 and T9961, MR 16269's CmmDiamondChain and nofib's puzzle at -O0, -O1 and -O2, the width comparison changes the compiler's instructions and allocation hardly at all. livenessCyclic takes the blocks to walk highest position in the SCC first. With them taken in the order queued, the compiler ran 4.3% more instructions and allocated 5.5% more compiling CmmDiamondChain at -O0, and 3.6% and 4.5% more at -O1 and -O2; with the lowest taken first, 5.7% more instructions at -O0. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - c796dc28 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Fill in liveBorn only for the graph allocator and -ddump-asm-liveness The liveness pass recorded, for every instruction, the registers born there (liveBorn), which costs a forward walk over every instruction of every block. Only the graph allocator and -ddump-asm-liveness use it. regLivenessBorn is now a pass of its own, which the graph allocator, its iterative variant included, runs on its input and again after recomputing liveness, and which CmmToAsm runs only for the dump. The generated code is the same, with the linear allocator and with -fregs-graph. The stage-1 compiler allocates 2.5% less compiling perf/compiler's T3294 at -O0 and 0.90% less at -O, 1.8% less compiling T12707 at -O0 and 0.63% less at -O, 1.6% less compiling T783 at -O0 and 0.29% less at -O, and 2.1% less compiling T9961 at -O0; with -fregs-graph it allocates up to 0.3% more (T9961 at -O0). Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.73% less. Figures that the per-commit measurements do not cover were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 6749b2c0 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Prefer the register a vreg is moved into where it dies The linear allocator preferred, for a vreg, the first register it was recorded in on entry to any block (findPrefRealReg); a new Note, [The first jump into a block fixes its registers], says what the first jump into a block decides, that register included. The allocator now has preferences, tried best first. firstFreeInOrder takes the free registers of the vreg's class and returns the first preference among them, else the first of them. allocRegsAndSpill_spill takes its choice, and so does saveClobberedTemps, which took the first free register where it moves a value out of a clobbered one. This commit adds one preference, ahead of the first-used register: the real register the current block moves the vreg into where the vreg dies. A value computed into a vreg that the block then moves into R1, before an evaluation or a return, is computed in R1, and the move, now from a register to itself, is dropped by genRaInsn. The first-used register, which keeps a loop variable in one register at both ends of a loop, gains nothing for a value that dies in the block. Ranked after it, the new preference cost nofib's scs 0.2% more instructions once later commits changed the order of the free registers: a spilled value was reloaded into its first-used register and then moved into R1's register. processBlock builds, for each block, the map from a vreg to the register the block moves it into where it dies (dyingMoves, rc_moveDests). The preference is taken from Andreas Klebinger's draft MR 16693, whose choice of a free register prefers the real register a vreg is moved into where it dies, in any block (ISSUE 27742); this commit takes the moves of the current block, a subset of those. The map lives in a record of its own, RA_Context, which RA_State holds in one strict field (ra_context), rather than in RA_State itself, where an unused field alone makes the compiler allocate 0.3% more compiling T3294 at -O0. The NCG configuration, which the allocator uses but does not update either, moves there too (rc_config, was ra_config), and runR takes the context in its place. The expected assembly of codeGen/should_gen_asm's T24813 loses the movq before each function's jmp: each popcount is now computed in R1. This applies on every target the linear allocator serves; the figures below are x86-64's. Measured against the parent commit, in instructions: nofib's programs, linked with the same libraries for both, take 0.25% fewer (0.26% at -O1, 0.73% at -O0), none as much as 0.2% more beyond their run-to-run noise; vector's benchmarks 0.27% fewer, none more; containers' 0.40% fewer, none as much as 0.1% more beyond their noise; megaparsec's 0.51% fewer (skipSomeTill 1.3%, endBy1 1.2%), none more; fannkuch-redux moves by no more than its noise at -O2 and -O1. No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.11% more compiling perf/compiler's T12707 at -O0, 0.19% more compiling T783, and 0.088% more compiling T9961; compiling T3294 its allocation moves by less than 0.1%. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 3be4da97 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Prefer a vreg's register at a recorded jump target (ISSUE 27980) firstFreeInOrder now puts first the register the vreg has on entry to a jump target of the current block whose assignment is already recorded (jumpLocRegs), such as a loop header jumped to from the loop's end: in that register the vreg needs no fixup move at the jump. For a target not yet reached, it takes the recorded assignments of the blocks that target jumps to, up to three jumps on. The first-used register, which a loop variable took until now, is the one the vreg was recorded in by whichever block recorded it first, which need not be the target. processBlock looks up the recorded assignments of the block's jump targets once, when the block starts (rc_jumpLocs, in RA_Context), taking the targets from a map of each block's jump targets that linearRegAlloc' builds once for the procedure (jumpSuccs): a target's assignment is recorded only at the block's jumps, after which no preference is looked up. Built lazily, that map makes the compiler allocate 0.3% more compiling perf/compiler's T3294 at -O0. In ISSUE 27980's reproducer the loop's continuation then reloads a variable straight into the register the loop header has it in, and the fixup block goes away. vector's quickhull and nofib's sphere and fibheaps show the same pattern, a rotation through a spill slot gone. It is a preference, applying where the block that gives the vreg a register jumps to a target whose assignment is recorded and the vreg's register there is free; the fixups of ISSUE 27800, of which ISSUE 27980 was closed as a duplicate, stay. The test, T27980, is the Cmm of ISSUE 27980's reproducer, its allocator statistics (-ddump-asm-stats) searched for fixup moves: with the parent commit's compiler the loop's back edge pays one. This applies on every target the linear allocator serves; the figures below are x86-64's. Measured against the parent commit, in instructions: nofib's sphere takes 0.27% fewer at -O2 and fibheaps 0.24% fewer at -O1, vector's quickhull 0.68% fewer at -O1, and no other program of nofib's, benchmark of vector's or fannkuch-redux moves by more than its noise; containers' benchmarks take 0.010% fewer (intset mapMonotonic 1.3%) and megaparsec's 0.006% fewer (hexadecimal.4000 0.12%), none as much as 0.1% more beyond their noise. No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.34%, 0.56% and 0.50% more compiling perf/compiler's T12707, T783 and T9961 at -O0, 0.16% and 0.20% more compiling T12707 and T783 at -O, and 0.32% more compiling MR 16269's CmmDiamondChain at -O1 and -O2, and 0.041% less compiling T3294 at -O0; the stage-2 compiler allocates 0.095%, 0.098% and 0.23% more compiling nofib's programs at -O2, -O1 and -O0 (geometric means). Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear allocates 25% more (3.26 against 2.60 GB). Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 67dce345 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Prefer the register a later block moves a vreg into where it dies firstFreeInOrder now has a last preference: the real register a block the vreg is live into moves it into where it dies, for a vreg computed blocks earlier, such as R1 for a value evaluated some blocks after it is computed (wideMoveDests, once a procedure; rc_wideDests). The blocks that follow a failed heap or stack check, such as those calling the garbage collector, do not count: the move there seldom runs, and the register it names can cost a move in the hot code. The preference is left out where that register is live together with the vreg somewhere, which a walk of the blocks finds: at a block's entry, after an instruction's writes, and where a vreg born while the vreg is live is moved into that register where it dies, in the block it is born in. The walk follows a vreg on into the vreg it is moved into where it dies, to which the allocator gives the same register, dropping the move; and it takes an instruction's writes from its register usage, liveBorn being filled in only for the graph allocator and the liveness dump. It visits only the blocks a destination is live into or written in, a move into one where a vreg dies included, as elsewhere no destination is live during the walk; and the candidates and the moves of a vreg into another where it dies, which the walk follows, are found in one pass over the procedure's blocks. Nor is it taken where another vreg the block reads or writes, with no location yet, has the register as its first-used one (rc_claims): without this, in vector's leaffix and listRank at -O1 a bound or an array reloaded after a call took its wide destination, displacing the values whose first-used register it is, and the loop's latch fixups grew from three instructions to five and six. A vreg already given a location claims nothing, so that a literal in intset instanceOrd:dense keeps its wide destination where an already coalesced vreg has it as its first-used register. processBlock's claims take an instruction's register usage from its liveness, where it has one, rather than computing it again. dyingMoves now gives moves into vregs as well, and is INLINE: out of line it makes the compiler allocate 1.0% more compiling perf/compiler's T3294 at -O0. This preference and the earlier one for the current block's moves ("Prefer the register a vreg is moved into where it dies") together overlap with that of Andreas Klebinger's draft MR 16693, the real register a vreg is moved into where it dies, in any block. Counting those blocks, in containers' map foldMap_traverseSum a node and its field both had %rbx as their destination, the field from the hot block that evaluates it, the node only from the heap check's failure block, which calls the garbage collector; the node, allocated first, took %rbx, and the field, given %rax, moved into %rbx at every evaluation: 1.5% more instructions. CmmToAsm takes those blocks from checkFailures (allocCold) and passes them to the linear allocator, wherever the backend maintains the CFG, -finfo-table-map or not; that is on x86-64 only, and elsewhere the set is empty. Leaving out only the failure targets that no other edge enters, as an earlier form of this change did, changes no code in perf/compiler's T3294, T12707, T783 and T9961 or in containers' benchmarks, and makes the compiler allocate slightly more. The rule for a vreg born while the vreg is live keeps the register for the later vreg, which its own block moves into it. Without it, in containers' graph buildG the loop's index and lower bound took R2's and R3's registers, which the block making the loop's call needed for its arguments, and that block ended with three moves an edge, 3.3% more instructions. Counting every vreg born while the vreg is live and moved into the register in any block made containers' map insertWith take 3% more instructions: its value argument arrives in R3 and is passed in R3 to both recursive calls, and the node's key, born later in the loop and moved into R3 in another block, made it lose R3 as a preference, so every iteration moved it out of R3 and back. Note [Frequencies before register allocation] gains a bullet saying that where blocks give a vreg different destinations the last block's wins, with a TODO at wideMoveDests: taking the hottest block's instead, by mkGlobalWeights, moved containers' benchmarks both ways by up to 1.4% and cost 0.24% more compile allocation, its estimate made for this alone. A comment there notes that a destination no allocator hands out, Sp, Hp or BaseReg, stays a candidate; leaving those out changed no code measured and costs compile allocation. Where no preference is free, firstFreeInOrder now leaves out, while others remain, the free registers the current block moves another vreg into where it dies: a vreg given one would keep the other from being computed in it, or have to move out of its way. Those registers are kept as a mask by register number, the first free register taken without filtering the list where the block moves no other vreg into a register where it dies, and the claims are walked only where no earlier preference is free and the wide destination is, so that the compiler's allocation compiling a procedure of many C calls grows with the procedure as at the parent. Without this, containers' graphFromEdges and stronglyConnCompR took up to 1.1% more instructions at -O1: the index-error block of their key lookup passes lo and hi in R3 and R4, so the new preference gives them those registers in the lookup's loop, and the array element, which has no preference, took the first free register, R1's, into which the loop moves the key before storing the element: every probe moved the element out of it first. This applies on every target the linear allocator serves; the figures below are x86-64's. Measured against the parent commit, in instructions: nofib's programs take 0.27% fewer (0.28% at -O1, 0.25% at -O0), none as much as 0.2% more beyond their run-to-run noise; vector's benchmarks 0.26% fewer (generateIO 3.8%), none more; megaparsec's 0.22% fewer (skipCount 0.9%, choice 0.6%), none more at -O2; fannkuch-redux moves by no more than its noise. The benchmarks of containers take 0.70% fewer (intset fromAscList:sparse:fusion 6.3%, intmap symmetricDifference up to 5.4%). No benchmark's allocation changes beyond nofib's run-to-run noise. Counting the failure blocks' moves, the stage-1 compiler allocates 0.18% more compiling perf/compiler's T3294 at -O0, 0.27% more compiling T12707, 0.19% more compiling T783, and 0.19% more compiling T9961; leaving them out takes back half or more of each. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.12% more. It runs 0.51% more instructions than the parent's compiling CmmDiamondChain at -O0 and 0.40% and 0.41% more at -O1 and -O2, 0.87% more compiling T12707 at -O0 and 0.63% to 0.70% more compiling T3294, T783 and T9961 at -O0. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear allocates 67% more (5.43 against 3.26 GB). Some rows rise, and a later commit takes back each one this paragraph names by undoing its cause. At -O1 megaparsec's endBy takes up to 0.49% more: its loop's join fixup, a cycle through the C stack that exists because the block the garbage collector returns to records the join's registers, gains a move an element; the commit after the next, "Allocate the blocks the garbage collector returns to last", removes the whole fixup, and with it the same loop's rotation in containers' map alter insert, 1.3% more here, and alterF alter insert. containers' graph buildG takes up to 2.2% more, its loop index, given no preference, now taking R1's register, which the call at the loop's end needs, so that moves on every edge remain, and intmap index 0.54% more, and in orthotope's A2T benchmark sumA and productA over large broadcast boxed arrays 3.4% to 3.6% more, the element passing through R1's register one move more an element; "Order x86-64 free registers around R1 and clobbers (ISSUE 27981)" takes all three back, returning buildG's block to the shape it has at "Prefer a vreg's register at a recorded jump target (ISSUE 27980)" and loading A2T's element straight into R1. vector's listRank takes 2.0M more instructions at -O1, and A2T's convert.g and convertE.g over large strided boxed arrays 18.75% more and its max.g and min.g 8.0% more, their rnf loop swapping its index through R1's register, three moves an element; "Allocate a loop before a continuation that enters it" takes both back: in listRank the block before the join loads straight into the join's registers, and the cycle through 0x40(%rsp) that holds this commit's move is gone, and the rnf loop's swap is gone. The rows of containers' intmap symmetricDifference-block, intmap and intset union-block, map fromDescListWithKey:fusion and map insertWith', and IntMap's and IntSet's union-disj_sn_swap and union-disj_tn_swap at -O2, two instructions more each by union-block's moves run once, are a trade: each pays moves in one procedure, following from the register choices the preference makes, with no local fix known; leaving the preference out reverts them and gives back its gains. Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 0fd144d7 by Mikolaj Konarski at 2026-11-13T19:46:56+01:00 Put a block's reloads after its leading unwind in stack layout To move into a merge request of its own, together with "Keep Sp put across loops and tag tests in stack layout". Under -g, maybeAddSpAdj starts each block's middle with an unwind giving the block's Sp rule, and insertReloadsAsNeeded puts a proc point's reloads before it, so that they run under the rule of the block laid out before this one. At a return point that rule also covers the return address (Note [Info Offset] in GHC.CmmToAsm.Dwarf.Types), and at -O0, where no sinking moves the reloads, the unwind tables are wrong there, on master at 58 return points of nofib's multiplier, primes, puzzle and para (13, 0, 12 and 33) compiled at -O0 -g. The next two commits make it frequent at -O0: the allocator moves the blocks the garbage collector returns to, and then the continuations that enter a loop making no call, with the SCCs only they lead to, to the end of its output, so that such a continuation no longer follows its call block. withReloads puts the reloads after a leading unwind. Without -g a middle starts with none and the code is the same: compiled by this commit, the four programs at -O0, -O1 and -O2 and the 15 compile-cost cells give the same objects and assembly; with -g only their -O0 output differs, and at -O0 none of their return points is under a wrong rule. Cost: withReloads is one foldr, which fuses with insertReloads's comprehension as the fold it replaces did. Compiling T3294 at -O0, -O and -O2 takes the stage-1 compiler 0.013%, 0.009% and 0.008% fewer instructions; the other compile-cost cells, and nofib's puzzle at -O2 compiled by the stage-2 compiler, change by at most 0.002% in instructions, and allocation falls by at most 0.011% in every cell. Assisted-by: Claude Opus 5.5 - - - - - d2be5194 by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Allocate the blocks the garbage collector returns to last The linear allocator records, at the first jump it allocates into a block, the registers the block starts with, and later jumps into the block move their values to match. linearRA_SCCs allocated the SCCs in order, so the block the garbage collector returns to after a heap or stack check fails, which jumps back into the block that made the check, could be allocated before the hot path reached that block, and so fix the registers it starts with. In containers' map alter the block that builds the new node makes such a check; its return block, allocated first, reloaded the new subtree into %rdi, R4, where the rebalancing call takes it, while the hot path still held the other subtree there, so the hot path reached the block through a fixup block rotating registers at every level the insertion returns through. linearRA_SCCs now allocates those return blocks (the procedure's entry blocks in the set checkFailures gives, which it now takes, those in a cycle excepted), and any SCC only they lead to, after the others, so that another predecessor, in map alter the hot path, records the registers and the return block pays the fixup. As it now tests every block for whether a jump has reached it, it looks the entry blocks up in a set built once rather than in their list. This commit overlaps with Sylvain Henry's MR 16673 (ISSUE 27800), read before this commit was written: both defer, in linearRA_SCCs, return blocks outside cycles; MR 16673 those that jump into a loop, calls' continuations included, with the acyclic blocks only they lead to, and this commit those the garbage collector returns to, whether or not they jump into a loop, with any SCC only they lead to. Taking no wide move destination while allocating such a block, instead, fixes map alter but makes map insertWith take 3% more instructions, the mirror case: its return block, allocated first, reloads the value argument into R3's %rsi, its wide destination, where the hot path has it; without that destination it reloads it into %rax, and the hot path moves it out of %rsi and back at every level. Note [Frequencies before register allocation] gains a bullet saying that checkFailures also counts as cold blocks the hot path may run, a continuation that a call returns to as well and a failure target that another edge enters, and that an estimate computed in a Cmm pass could replace the classification; linearRA_SCCs and checkFailures gain TODOs pointing there. Where such a continuation is on the path into a loop, deferring it measured better than leaving it out of the set: the loop is then allocated first, starting from the block the garbage collector returns to from the loop's own check, so that the path into the loop pays the moves once and the loop's latches none (containers' set-benchmarks); leaving such continuations out costs nofib's scs 1.1% more instructions and vector's maximumOn 2.9%, and leaving out such failure targets changes no code measured and costs compile allocation. Allocating a loop before the path into it on purpose, by deferring the blocks that jump into an SCC holding an entry block, costs fannkuch-redux 13% at -O1, whose inner loop lies in its outer loop's SCC. MR 16673's deferral, of every return continuation outside a cycle that jumps into a loop, is not used either, because it was found incorrect: it defers as cold a continuation that is itself inside a loop through the Haskell stack, and fannkuch-redux then runs 16 to 19% more instructions. From "Allocate hotter SCCs first, the procedure's first block before them" on, the deferral orders the SCCs only where no block frequencies are estimated, on x86-64 without -fcmm-static-pred, as at -O0; at -O1 and -O2 that commit's order replaces it. With the return blocks allocated last, a block that reloads a value can find the vreg's first-used register, the one whichever block recorded the vreg first gave it, to be another value's: in containers' map fromList-distinctAsc at -O2 such a reload took it over its own wide destination. firstFreeInOrder now passes over the first-used register for the wide destination where a walk from the current block's jump targets, through the blocks the vreg is live into and stopping at those whose assignment is recorded, reaches no recorded block but reaches one that moves the vreg into the wide destination where it dies, and the value live into a block recorded with the vreg in the first-used register reaches none of the blocks the walk passed (staleWalk, staleMeets). The vreg is then marked (markStaleFirst), and for a marked vreg whose walk reaches a recorded block holding it in another free register, that register is taken: in sequence's update.100 and adjust.100 at -O1, three continuations reloading into the same vregs then agree, where the later two kept the stale register and paid a swap through the C stack. And genRaInsn reloads a vreg that an instruction only moves, where it dies, into a register free by then straight into that register, and drops the move (reload_into), as in map union at -O2. Measured against the parent commit, in instructions: nofib's programs take 0.11% fewer (wheel-sieve2 2.2%; 0.18% at -O1, fasta 10.7%), none but knights at -O1, below, as much as 0.2% more beyond their run-to-run noise; vector's benchmarks 1.2% fewer (maximumOn 17%, minimumOn 15%); megaparsec's 3.7% fewer (endBy 22%, skipMany 16%); fannkuch-redux moves by no more than its noise. containers' benchmarks take 0.21% fewer (intset fromList:worstCase 8.2%, and map alter insert, the case above, 1.3%). No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.12%, 0.15% and 0.15% more compiling perf/compiler's T12707, T783 and T9961 at -O0, and 0.073% or less more in its other cells, MR 16269's CmmDiamondChain's included; the stage-2 compiler allocates 0.047%, 0.052% and 0.12% more compiling nofib's programs at -O2, -O1 and -O0 (geometric means). Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear allocates 19% more (6.45 against 5.43 GB) and GHC.CmmToAsm.Reg.Linear.Base 16% more (0.51 against 0.44 GB). At -O1, vector's permutation benchmarks take 4.65% to 5.26% more, quickhull 2.6% more and nofib's knights 0.52% more, and in orthotope's A2T benchmark Summed's sumView over boxed arrays up to 1% more and summed reduce over small dense boxed arrays 4.4% more: in their loops another predecessor now records a join's registers, one where a loop value with no preference has taken R1's %rbx, and the predecessors that receive an evaluated value in %rbx reach the join through a fixup that swaps or rotates registers at every iteration. "Order x86-64 free registers around R1 and clobbers (ISSUE 27981)", which puts %rbx last in x86-64's fallback order, removes these moves in the same blocks; the rotation left in quickhull's split loop is there before this commit. A2T's generate.scalar over strided Storable arrays takes 1.6% more, a swap through the C stack and two moves into R1's %rbx at a join once a call, which that commit removes too. The other rises are the deferral's price, and leaving the deferral out reverts them. The blocks the garbage collector returns to now pay the moves into the registers the hot path recorded, by design: containers' main426, $wascLinkTop and $sgo2 pay more instructions a call at -O1; and megaparsec's many pays swaps through the C stack at every collection, the hot path having had no fixup to lose. With the allocation order changed, other blocks move values between registers, with no local fix known: containers' intset fromAscList:sparse:fusion, map fromDescListWithKey, fromDistinctDescList, fromAscListWithKey and fromList-distinctAsc:fusion (-O1), IntSet's symmetricDifference-block_sn_swap, symmetricDifference-disj_tn_swap and difference-disj_nt and sequence update.10, and megaparsec's endBy1. A2T's rotate.inner over large dense Storable arrays takes 1.7% more, its loop reassigned; "Allocate a loop before a continuation that enters it" removes about half of that, a store and a reload through the C stack. In vector's findIndexR, which takes 3.2% more at -O1, the procedure's entry now records the loop's registers, with the predicate in R2's %r14, where it arrives, and another loop value in R1's %rbx; as the loop calls the predicate through %rbx, every iteration moves that value out of %rbx and the predicate in, by way of %rdx: more moves than before. "Order x86-64 free registers around R1 and clobbers (ISSUE 27981)" puts the other value elsewhere, removing the move out of %rbx; not deferring a return block that a warm block enters takes back the rest, but costs nofib's fasta 13 instructions an iteration at -O1, and telling a loop's only latch from a colder second latch needs block frequencies. At -O1 megaparsec's skipMany takes 0.95% to 0.96% more, a move an element that lasts until "Keep Sp put across loops and tag tests in stack layout" removes it: the hot path, now allocated before the block the garbage collector returns to, takes the first free register where the join's recorded one is expected. Leaving the deferral out reverts it, with most of the procedures of megaparsec's bench-speed that this commit changes; extending the claims of "Prefer the register a later block moves a vreg into where it dies" to the vregs a jump target writes removes the move but makes many of containers' benchmarks take more instructions, intmap fromAscList 3.3% and intersection-mix_nn 1.0% among them. Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - c6bdd7ab by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Allocate a loop before a continuation that enters it The linear register allocator gives a block the assignment of the first jump into it that it allocates, and the SCC order puts a return continuation before a loop it jumps into. Where the continuation's jump was the first into a block of the loop, it decided that block's registers, and the loop's own edges into the block paid fixup moves at every iteration: in the reproducer of ISSUE 27800, two swaps an iteration. Defer such a continuation, as the blocks the garbage collector returns to are deferred, so that the loop's own edges decide and the fixup goes on the continuation's edge into the loop. This takes from MR 16673, by Sylvain Henry, its deferral of a return continuation that jumps into a loop, which is what fixes the issue there, as an extension of the series' own deferral, not as MR 16673's code, and adds two conditions it lacks: * the loop calls nothing: a loop that calls C keeps its values in spill slots, which a deferred continuation that is hot through the Haskell stack then pays for (nofib's fannkuch-redux ran 16% more instructions with the deferral unconditional); * no assignment is recorded yet for the block the continuation jumps into: once another jump has recorded one, deferring changes only the order of allocation, by which block layout breaks its ties (containers' intset fromAscList, one jump more an element). The deferral remains a bet that a continuation runs less often than the loop it jumps into, and it loses where the continuation is the return point of a call made at every iteration of that loop, which then pays the fixup at every iteration instead: megaparsec's reachOffsetNoLine takes 0.96% more instructions at -O2 and reachOffset 0.28% to 0.36% more, nofib's mandel2 0.33% more, and containers' fused fromDistinctDescList rows 8.1% to 8.8% more at -O1; it loses as well where the loop runs no trip or few, the continuation paying the fixup once a call: in orthotope's A2T benchmark convert.g over empty strided boxed arrays takes 1.1% more, summed force.narrow over empty dense Storable arrays 0.5% more and rev over small scalar Storable ones 0.4% more. This is the trade the deferral makes, its toggle the deferral itself, which reverts both these and the fromAscList family's gains: the cases differ only in how often a call path runs, on which no structural order depends. A third condition, deferring only a continuation whose call the loop it jumps into does not reach, breaks T27800, leaving a swap through a spill slot on both hot edges, loses every gain of containers' fromAscList family and vector's listRank and awshcc, makes nofib's fasta take 10.3% more at -O2, and leaves megaparsec's reachOffsetNoLine where this commit puts it. A2T's generate.scalar over strided Unboxed arrays takes 2.0% more, a swap through the C stack and two moves into R1's %rbx at a join once a call, which "Order x86-64 free registers around R1 and clobbers (ISSUE 27981)" removes. From "Allocate hotter SCCs first, the procedure's first block before them" on, this deferral acts only where no block frequencies are estimated: on x86-64 without -fcmm-static-pred, as at -O0, and on the other targets; at -O1 and -O2 on x86-64 that commit's order replaces it, and T27800, compiled at -O, exercises that order. The test, T27800, is the Cmm of MR 16673's T27800.cmm, its assembly searched for swaps and spill slots: the loop's edges carry neither, and T27800.stderr expects the lines of the fixup on the cold edge out of the continuation, a swap through a spill slot. Measured against the parent commit, in instructions: vector's benchmarks take 0.96% fewer at -O1 (hybcc 5.9%, listRank 5.8%, awshcc 3.2%, leaffix 3.8%) and move by no more than their noise at -O2; nofib's programs move by less than 0.01% at -O2 and at -O1 in geometric mean, simple taking 0.28% and 0.21% more; containers' benchmarks move by less than 0.01% at both levels in geometric mean, the fromAscList family taking 2.9% to 8.1% fewer at -O2, its swap through a spill slot on each back edge gone, though intmap fromAscList:fusion takes 1.3% more there and the fused fromDistinctAscList rows 2.3% more at -O1, and graphFromEdges up to 1.7% fewer at -O1; fannkuch-redux moves by no more than its noise. No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler allocates at most 0.021% more compiling perf/compiler's T3294, T12707, T783 and T9961. Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 3d5ca65c by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Skip registers written before a saved value's next read (ISSUE 26631) saveClobberedTemps, saving a value out of a register an instruction clobbers, such as an argument register of a C call, moved it into the first free register in order, even one a later instruction of the block writes before it reads the value again; then the value moved again or was spilled there. It now leaves out the registers the rest of the block writes before it next reads the value (unwrittenBeforeRead), and where every free register is one, spills the value at once. On System V every float and vector register is caller-saved, so such a value live across a C call ends in memory anyway: in simd013 the moves and a spill before the call become a spill (ISSUE 26631). Writes in later blocks are not looked at. containers' intmap and map mapMaybe and nofib's x2n1 and reverse-complement show the pattern: values crossing a C call stored at once rather than first moved into a caller-saved register, and mapMaybe's divisor kept out of %rdx, which cqto writes. Spilling at once wherever the first free register is written somewhere in the value's live range instead, by the clobber map that "Order x86-64 free registers around R1 and clobbers (ISSUE 27981)" builds (rc_clobbers), makes fannkuch-redux take 1.1% more instructions: a loop bound kept in %rbx across a memcpy call is spilled and reloaded at every iteration, %rbx being written elsewhere in the bound's live range, though not before the loop reads it. This applies on every target the linear allocator serves; the figures below are x86-64's. Measured against the parent commit, in instructions: nofib's programs take 0.034% fewer (k-nucleotide 2.0%), none as much as 0.2% more; fannkuch-redux 0.32% fewer (0.35% at -O1); containers' benchmarks 0.001% fewer (0.003% at -O1), none more beyond their noise; megaparsec's 0.018% fewer (string 0.17%), none more; vector's benchmarks move by no more than their noise. No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler's allocation compiling perf/compiler's T3294, T12707, T783 and T9961 moves by 0.010% or less. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 4c8fb37c by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Assign literals after computed values at the end of a block To move into a merge request of its own, together with "Gather a Cmm sum's literals into one constant, and narrow != as ==", "Address (i << s) + lit on x86 by a scaled index with no base", "Take the constant out of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset into any sum with a constant" and "Drop the assignments that only a discarded assignment read". GHC.Cmm.Sink emits the assignments it sinks no further at the end of a block, in their order. An assignment of a literal to a local register now goes after the later ones where each of those assigns, to another local register, a literal or the result of a machine operation that reads neither that register nor the literal's. A literal reads neither memory nor a register, and none of the assignments it passes reads or writes its register, so every value stays the same. Set first, a constant can take the register that a later value is to be in at the block's end, while the value's operands still hold the register the constant is to be in. In Data.Text's UTF-8 decoding, as inlined into megaparsec's benchmarks, the ASCII path sets the width, 1, and then the character, the zero-extended byte, and jumps to the join, whose recorded assignment has the width in %r14 and the character in %rbx. Once a later commit makes %rbx x86-64's last choice, the byte is loaded into %r14; set first, the width would then take %rbx and the character %r14, and the join's fixup would swap them at every character. Set last, the width takes %r14, and the byte is zero-extended into %rbx. A copy or an update in place keeps a literal before it: in a trial that let it pass them as well, the literal changed the registers of a join's recorded assignment in megaparsec's manyTill benchmark and of a loop head's in Text.Megaparsec.Stream's reachOffset, whose other predecessors then paid a move a character. At the series' end, where the gains measured below are gone, what the commit keeps is in the same decoding's paths for 2- to 4-byte characters: without it, each sets the width before the character while %rax still holds the array, and ends with one more move. A loop of takeWhile isNumber and foldl' over digits 2, 3 or 4 bytes wide then runs 0.99 more instructions a character, 0.9% to 1.2% of the loop, and no more at 1 byte; none of megaparsec's benchmarks has non-ASCII input. Measured on x86-64 against its parent: megaparsec's benchmarks run 0.029% fewer instructions over those stable across runs (someTill 0.72%), none more. Of nofib's programs only cacheprof's, k-nucleotide's and veritas's objects change size, cacheprof's in the order of its instructions alone and k-nucleotide's in its registers, and none moves by as much as 0.2%; containers' and vector's benchmarks move by no more than their noise. The assembly of perf/compiler's T3294, T12707, T783 and T9961 at -O0 and -O is the same; at -O the stage-1 compiler allocates up to 0.011% more compiling them (T783) and 0.007% more compiling MR 16269's CmmDiamondChain at -O1 and -O2, and at -O0 up to 0.010% more (T783). The lines below name the perf tests that the series as a whole moves below their windows against master, and ManyConstructors, T5631, T9630 and WWRec, which it moves down within theirs; this commit by itself moves none of them out of its window. Metric Decrease: CoOpt_Read ManyAlternatives ManyConstructors T10421 T12227 T12425 T12707 T13035 T13056 T13253 T13253-spj T13379 T13960 T15164 T15304 T15630 T15630a T15703 T16577 T18140 T18282 T18698a T18698b T18730 T18923 T1969 T19695 T20049 T20261 T21839c T24471 T26425 T26989 T3064 T3294 T4801 T5030 T5321FD T5321Fun T5631 T5642 T6048 T783 T9198 T9233 T9630 WWRec Assisted-by: Claude Opus 5.5 - - - - - 619e5926 by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Prefer a loop variable's register for the value moved into it A vreg that the current block moves, where it dies, into another vreg, such as a loop's next index moved into the index variable before the jump back to the loop's header, now prefers the register the recorded assignment of a jump target of the block gives that other vreg, as it prefers a real register the block moves it into: processBlock adds such moves to rc_moveDests, from rc_jumpLocs. In that register the move goes away, and at the jump the other vreg is where the target's recorded assignment has it. A move counts only where the block does not write its source again (dyingMovesLast): a preference is looked up by the vreg, so it would otherwise reach the vreg's later value. Where such a move counted, in nofib's gcd, whose loop ends by shifting loop variables (t2C8 := t2Cb, then t2Cb := a new value), the new value took the register the loop's header gives t2C8, and the jump to the header then had to exchange two registers through a stack slot: 0.4% more instructions. dyingMovesLast shares dyingMoves' test of a move where the vreg dies (dyingMove). The moves into real registers include those of a vreg the block writes again after the move, its later value then preferring that register too; leaving them out changed no code measured and costs compile time. This applies on every target the linear allocator serves; the figures below are x86-64's. Measured against the parent commit, in instructions: containers' benchmarks take 0.11% fewer: map lookup absent and alterF lookup absent 5.2% fewer, and lookupge-map's GE Twan 2.8% to 3.4%; fannkuch-redux 0.014% fewer; nofib's programs and vector's benchmarks move by no more than their noise. No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler's allocation compiling perf/compiler's T3294, T12707, T783 and T9961 moves by 0.010% or less. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - ac016387 by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Order x86-64 free registers around R1 and clobbers (ISSUE 27981) On x86-64, where none of its preferences is free, a vreg now takes R1's register, %rbx, last in each of the two parts below: an evaluation and a return write it, so a value given it may have to move out of their way, and a loop variable given it at the loop's entry moves at every iteration (ISSUE 27981). Before the others it takes the registers no instruction writes while the vreg is live past the write: for a vreg live across a C call, these are the registers the call preserves, on System V R2's %r14 and %rbx, and for one still live where an argument is moved into R2's %r14 for a jump, they exclude %r14. Given a register such an instruction writes, the vreg would have to move out of the way. Where no preference is free, firstFreeInOrder leaves out the free registers the block moves other vregs into where they die, and takes the first of the rest; on x86-64, where the allocator's context holds regClobbers' map (rc_clobbers, Nothing elsewhere), it takes the one fallbackReg picks, the first free register in this order, R1's register taken from a constant rather than from globalRegMaybe at every call. Where the block moves no other vreg into a register where it dies, firstFreeInOrder hands fallbackReg the free registers themselves, rather than a filtered copy. In the reproducer of ISSUE 27981 this commit already removes the back edge's fixups; the next commit removes the cause the issue names. In T27800, the test of ISSUE 27800, the continuation's edge into the loop no longer swaps through a spill slot, and T27800.stderr, which expected those lines, is deleted. regClobbers finds, for each vreg, the registers written while it is live, once a procedure on x86-64: the liveness pass now records, at each instruction that writes a real register, the registers live after it (liveAcross), and regClobbers adds the written registers to every vreg among those that is live past the instruction, as bits by register number, finding the vregs an instruction writes once for the instruction rather than once for each vreg live past it; and firstFreeInOrder binds strictly the vreg's first-used preference, which noPrefs reads a second time. Only x86-64's fallback uses them, and on the other targets RA_Context's field is empty, so that no unread thunk keeps the procedure's code alive. A move of the vreg itself into a register is no such write. Where the vregs live past a write number more than 24, as at most divisions of MR 16269's CmmDiamondChain, regClobbers unites them with those live past the earlier writes of the same registers and marks each union's vregs once at the end, rather than looking each up at every write; a smaller set is marked a vreg at a time, and the masks are the same either way. It tests an instruction for registers live past it, a set the liveness pass leaves empty where the instruction writes no real register, before it computes the mask of the registers written, and counts a set's members only up to the threshold. Leaving out the writes in the blocks that follow a failed check costs containers' lookupge-intmap Milan lookups 0.5 to 1% more instructions, a failure block's write having kept a vreg, by accident, out of a register that a later vreg is moved into; Note [Frequencies before register allocation] gains a bullet on the case, with a TODO at regClobbers. Andreas Klebinger's draft MR 16693, read before this commit was written, charges a vreg for each register that an instruction in a loop starts writing while the vreg is live across it, and this order overlaps with that clobber cost: both steer a vreg away from the registers written while it is live, MR 16693 by a cost counted within loops, this commit by the order of the free registers, from the writes met anywhere the vreg is live. On x86-64, for a vreg that has preferences, all of them taken, fallbackReg also leaves out, where a free register would remain, the registers that the recorded assignment of a jump target of the block gives another vreg, so that the vreg does not take a register the jump will need for that one: a part of what ISSUE 26666 asks. fallbackReg also leaves out, where others remain, the free registers that the blocks up to three jumps ahead that the vreg is live into move another vreg into where it dies, the vreg's own such destinations excepted: given one, the vreg would keep the other from being computed in it, or have to move out of its way there. Not for a vreg live across a C call, which leaves its register at the call anyway: a block after the call, such as k-nucleotide's copy of a new key, would put it on an argument register that the call's own setup needs, and the arguments were swapped through %r9. Nor where a jump target not yet recorded that the vreg is live into has two or more predecessors, those after a failed heap or stack check not counted: its register there binds them all, and a walk from one of them reaching a rare exit put megaparsec's manyTill counter on a register its hot predecessor holds, a move in the join's fixup. With this look-ahead IntMap's union-mix_sn_swap, union-mix_nn and union-mix_nn_swap take fewer instructions at -O2, and at -O1 intmap fromAscList, fromAscList:fusion and intset fromAscList:sparse. The look-ahead costs the compiler instructions and allocation compiling perf/compiler's T3294 and MR 16269's CmmDiamondChain at -O0; in this commit's own figures the saving of R1's constant and of choosing the fallback by rc_clobbers cancels most of it. The look-ahead's walk keeps, for each block it walks on from with two jumps or more left, the most jumps it had left there, and walks on from the block again only with more, so that raising its limit of three would not make it exponential in the jumps; at three this costs hardly any more instructions compiling nofib's puzzle at -O2, and the code is the same. raInsn no longer drops a move from one vreg into another, giving the destination the source's register, where a jump target of the block whose assignment is recorded has the destination in a free register other than the source's and another vreg in the source's: the move then puts the destination where the target has it, and the jump does not have to swap it with that other vreg, as in containers' IntSet compare (intset instanceOrd:dense). Where no target has a vreg in the source's register, the move is dropped as before, the jump moving the destination on its own edge rather than the move running on every path out of the block. The expected assembly of codeGen/should_gen_asm's bytearray-memcpy-unroll and bytearray-memset-unroll names other registers now; the instructions and their order are the same. Simpler forms cost more. %rbx last for every vreg costs up to 3% more instructions in procedures that make C calls. %r14 first as well, wherever no vreg is live across a C call, gains in some loops but costs up to 3% more elsewhere, where %r14 is used later, for R2 or in a jump target's recorded assignment. Taking the registers a C call preserves first for every vreg live across one, ignoring every other write, makes fannkuch-redux take 1.3% more instructions: a loop variable live across a call elsewhere in the procedure is given %r14 and moves out of R2's way at every iteration. Measured against the parent commit, in instructions: nofib's programs take 0.40% fewer (fasta 5.3%, k-nucleotide 4.3%, bspt 2.4%; 0.48% at -O1, 0.097% at -O0), none as much as 0.2% more beyond their run-to-run noise; fannkuch-redux 0.22% fewer; vector's benchmarks 1.3% fewer (nextPermutationBijective 4.4%, findIndexR 3.4%), none more than 0.003%; containers' benchmarks 0.38% fewer (intset partition 6.1%, intset filter 5.2%, graph buildG 0.63% to 3.9%); megaparsec's benchmarks 1.6% fewer (reachOffsetNoLine 7.6%, many 6.8%). No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.25% more compiling perf/compiler's T3294, 0.31% more compiling T12707, 0.23% more compiling T783 and 0.32% more compiling T9961, each at -O0, and 0.080% or less at -O and -O2. Compiling MR 16269's CmmDiamondChain, it allocates 2.6% more at -O0 and 2.2% more at -O1 and -O2. A stage-1 compiler runs 3.4% more instructions than the parent's compiling CmmDiamondChain at -O0 and 2.8% more at -O1 and -O2, and 1.2% more compiling T9961 and 1.1% more compiling T3294 at -O0, every other cell under 1%. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear allocates 22% more (8.77 against 7.22 GB) and GHC.CmmToAsm.Reg.Liveness 14% more (2.77 against 2.43 GB). That compile cost is a trade, its toggle regClobbers' map: left empty, so that the fallback orders the free registers without the clobbering writes, it takes the commit's compile cost against its parent to 0.9% for CmmDiamondChain at -O0 and 0.75% at -O1 and -O2, and to 0.18% for T9961 at -O0; but the assembly of CmmDiamondChain, of T12707 and T3294 at -O0 and of T9961 at -O and -O2 changes, and so does that of nofib programs at each level, of which, compiled by stage-1 compilers over the same libraries and run as nofib runs them, shootout's fasta takes 5.5% more instructions at -O2, k-nucleotide 3.1% and fannkuch-redux 2.3% more, wheel-sieve2 1.2% and wheel-sieve1 1.1% more, and all of them together 0.25% more at -O2 and 0.15% at -O1 and the same to 0.01% at -O0, none 0.2% fewer. The map is kept, and its cost with it. The rises in containers are trades, each with a toggle. At -O1 IntSet's union-common and union-mix take 0.44% to 0.87% more, union-block 0.26% to 0.41% and IntMap's union-common 0.14% to 0.51%, and no later commit takes them back: union_info loads the subtree field into %rdi rather than %rsi, and each of its recursion-call blocks adds a move, the partition of the free registers by clobbering writes being tied, the field moved into %rsi on two paths while %rsi is written on the third; which side wins depends on how the input sets overlap. Not counting as clobbered a vreg's own dying-move destinations up to three jumps ahead, except for vregs live across a C call, takes them back, but makes intset fromAscList:sparse take 2.64% more, map fromListWith-desc and its siblings 0.87% to 1.08% more, IntSet's and IntMap's symmetricDifference common, mix and block rows 0.30% to 0.59% more and Map's union-common_nn 0.49% more (-O2), and costs 0.27% more compile allocation for T3294 at -O0. map fromListWith-desc:fusion takes 0.99% more at -O2: of four specialisations of one insertion loop, which share R4 between two subtree fields, the order wins three, and the variant that wins the fourth makes the other three take 1.0% to 1.1% more. At -O1 the fused fromAscList family, intmap lookup_misses and map fromList-distinctAsc:fusion take more by R1's place last in the order; R1 in its natural place reverts them, but brings back graph buildG's rise of "Prefer the register a later block moves a vreg into where it dies" (up to 2.2%) and makes intset folds:dense foldr'_maximum take 5.8% more. intset mapMonotonic takes 1.27% more at -O2, the order putting %rsi after %rax so that the hot path's reload cannot take %rax; leaving out the registers jump targets give other vregs for vregs without preferences too fixes it, but makes set alterF:insert:present take 2.4% more, alterF:delete:absent 2.7% and map fromAscList:fusion 1.9%. intset fromList:randomDups:fusion takes 0.55% more at -O1; R1 in its natural place for vregs that die in their block fixes it, but gives back folds:dense foldr'_maximum's gain (5.5%) and folds:sparse foldr'_maximum's (0.9%). Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 8fb13041 by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Free every register not live into a newly reached block (ISSUE 27981) On the first jump to a block, joinToTargets_first recorded, beside the block's assignment, the block's free registers, the source block's with those of the vregs not live into the target released, and initBlock started the block with them. A real register still allocated at the jump and not live into the target, R1 above all where it is allocatable, therefore stayed allocated in the target block until the block wrote it and that value died: a value the block reloads cannot go back to it, and the block's jumps may need fixup moves. initBlock now derives the free registers on entry to every block: every allocatable one but the real registers live into it and those holding the vregs of its recorded assignment, if it has one; a recorded assignment no longer carries free registers, and joinToTargets no longer computes the registers to release (to_free), nor needs FR. In its reproducer the previous commit already removes the fixups, so the reproducer does not show this fix alone; here its inline form runs fewer instructions an element. The test, T27981, is ISSUE 27981's reproducer, its allocator statistics searched for fixup moves: it passes with the parent commit's compiler, which already removes them, and fails with that commit's parent's, which puts two on the loop's back edge. allocateRealRegs marks the real registers among those live into a block allocated, and is INLINABLE, so that x86's allocator runs it specialised: with the pragma, the compiler runs up to 0.55% fewer instructions compiling MR 16269's CmmDiamondChain at -O0 than without it, and allocates up to 0.013% less compiling nofib's puzzle at -O0. initBlock takes the procedure's initial free registers from RA_Context (rc_initFree) rather than rebuild them for each block; runR starts the allocator with them too, and with an empty block assignment, register assignment and stack map, taking none of them as arguments; joinToTargets_first, left with two statements, is inlined by hand at its one call site. This applies on every target the linear allocator serves; the figures below are x86-64's. Measured against the parent commit, in instructions: nofib's programs, vector's benchmarks and fannkuch-redux move by no more than their noise; containers' benchmarks take 0.033% fewer (tree edges 1.4%, graph transposeG 1.3% and buildG 1.1%), none more beyond their noise, and megaparsec's 0.22% fewer (many 1.2%, sepEndBy 0.85%), none more. No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.15% less compiling perf/compiler's T3294, 0.72% less compiling T12707, 0.72% less compiling T783 and 1.0% less compiling T9961, each at -O0, and up to 0.24% less at -O and -O2. Compiling MR 16269's CmmDiamondChain, it allocates 4.2% less at -O0 and 3.5% less at -O1 and -O2. Assisted-by: Claude Opus 5.5 - - - - - 659956d9 by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Write the linear allocator's state only where it changes releaseRegs, which genRaInsn calls twice for every instruction, with the registers the instruction reads for the last time and those it writes that die at once, wrote the assignment and the free registers back to the allocator's state even where it had no register to release; saveClobberedTemps, for every instruction that writes a real register, folded over the whole assignment in the monad and wrote it back even where no value sat in a clobbered register. Each write builds a new RA_State. releaseRegs now returns at once where it has nothing to release, and saveClobberedTemps picks the values to save by a pure fold, in the order the monadic one took them, and writes the state only where there are some. The generated code is the same. The stage-1 compiler allocates 2.1% less compiling perf/compiler's T3294 at -O0 and 0.76% less at -O, 1.5% less compiling T12707 at -O0 and 0.49% less at -O, 1.3% less compiling T783 at -O0 and 0.22% less at -O, and 1.8% less compiling T9961 at -O0, though 0.008% less at -O. Compiling MR 16269's CmmDiamondChain, it allocates 4.9% less at -O0 and 4.0% less at -O1 and -O2. Assisted-by: Claude Opus 5.5 - - - - - 53b6a06a by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Find the linear allocator's spill candidates in one fold Where no register of a vreg's class is free, allocRegsAndSpill_spill frees the register of another vreg: the first one that is in a register and in a stack slot, else the first one only in a register, among those it need not keep. It found them by filtering the whole assignment to the vregs in a register, deleting those to keep, listing the rest and searching the list twice. It now folds over the assignment once, keeping the first vreg of each kind, in the order the list had them. The generated code is the same. The stage-1 compiler allocates 8.8% less compiling perf/compiler's T3294 at -O0 and 3.9% less at -O, and 0.50% less compiling T12707 at -O0; its allocation compiling T783 and T9961 falls by 0.016% or less. Compiling MR 16269's CmmDiamondChain, it allocates 0.39% less at -O0 and 0.31% less at -O1 and -O2. Assisted-by: Claude Opus 5.5 - - - - - e4c97fad by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Walk register assignments without listing them clobberRegs listed the whole assignment, for every instruction that writes a real register, to move the vregs that are in a clobbered register and in a stack slot to the slot only; it now folds over the assignment. joinToTargets_again listed the recorded assignment of a jump target and the current one, to compare them ignoring the formats; equalIgnoringFormats now compares the two maps themselves, by liftEq on their IntMaps rather than by the Eq instance of IgnoreFormat Loc, which makes the compiler run up to 0.11% fewer instructions compiling MR 16269's CmmDiamondChain at -O0 and allocate as much. The generated code is the same. The stage-1 compiler allocates up to 0.066% less (T9961 at -O0), and at most 0.010% more, compiling perf/compiler's T3294, T12707, T783 and T9961. Compiling MR 16269's CmmDiamondChain, it allocates 5.6% less at -O0 and 4.6% less at -O1 and -O2. Assisted-by: Claude Opus 5.5 - - - - - 5a41b907 by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Sort a procedure's blocks only where its first block is not first regAlloc sorted the linear allocator's blocks to keep the procedure's first block at the front; it now sorts them only where that block is not at the front already. The generated code is the same. The stage-1 compiler allocates 0.086% less compiling perf/compiler's T3294 at -O0, 0.32% less compiling T12707 at -O0 and 0.12% less at -O, 0.28% less compiling T783 at -O0 and 0.079% less at -O, and 0.47% less compiling T9961 at -O0. Assisted-by: Claude Opus 5.5 - - - - - 47df783a by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Compute the dying registers and the live-in map of liveness strictly liveness1 left, in each instruction's liveness, the registers read for the last time there and those written there that die at once as thunks, which the linear allocator forces at every instruction; livenessSCCs likewise left the map of the registers live into each block to be computed later, through the acyclic SCCs. They are now computed as the liveness pass goes. The generated code is the same. The stage-1 compiler allocates 0.74% less compiling perf/compiler's T3294 at -O0 and 0.26% less at -O, 0.56% less compiling T12707 at -O0 and 0.21% less at -O, 0.68% less compiling T783 at -O0 and 0.16% less at -O, and 0.69% less compiling T9961 at -O0. Assisted-by: Claude Opus 5.5 - - - - - 6f837348 by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Skip the address registers x86's mkRU would drop regUsageOfInstr on x86 and x86-64 added every register an address names to an instruction's register lists, and mkRU then filtered out the ones the allocators do not manage, such as Sp's %rbp, Hp's %r12 and BaseReg's %r13, copying each list that held one: those of every access to the stack or the heap. An address's registers that mkRU would drop are now left out where they are added. This commit is a subset of Sylvain Henry's MR 16843, whose register usage DSL adds each register, an address's included, only where the allocators manage it. The generated code is the same. The stage-1 compiler allocates 0.78% less compiling perf/compiler's T3294 at -O0 and 0.27% less at -O, 0.36% less compiling T12707 at -O0 and 0.12% less at -O, 0.32% less compiling T783 at -O0, and 0.22% less compiling T9961 at -O0. Assisted-by: Claude Opus 5.5 - - - - - 43134f47 by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 List a CFG's edges once in block layout sequenceChain listed the edges of the CFG twice, once for the chains it builds and once for the edges left between them; it now lists them once. The sets of the edges that buildChains and combineNeighbourhood fuse, master's Sets of pairs of BlockIds, are now LabelMaps from each block to the LabelSet of the blocks its fused edges enter, and combineNeighbourhood lists each of its chains once by taking it at the lowest of its ends, where master removed the repeats with nubOrd. The generated code is the same. The stage-1 compiler allocates 0.12% less compiling perf/compiler's T12707 at -O, 0.17% less compiling T783, and 0.031% less compiling T3294; at -O0 its allocation falls by 0.006% or less. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.28% less. Assisted-by: Claude Opus 5.5 - - - - - 9684751d by Mikolaj Konarski at 2026-11-13T19:46:57+01:00 Build no lists of results in calcFreqs calcFreqs, which static prediction runs for every procedure, built a list of results for each block's out-edges (forM in calcOutFreqs) and, for each block's predecessors, a list of Bools to test for irreducible flow and a list of probabilities to sum. It now uses forM_, anyM and a left fold from 0, which adds the probabilities in sum's order, so that the frequencies are the same, and so is the generated code. isBackEdge, master's, looks an edge up in an IntMap of IntSets rather than in a Set of pairs. At -O the stage-1 compiler allocates up to 0.094% less compiling perf/compiler's T3294, T12707, T783 and T9961 (T12707); at -O0, where static prediction is off, its allocation moves by 0.004% or less. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.29% less. Assisted-by: Claude Opus 5.5 - - - - - de64b698 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Give back edges no bonus where static prediction estimates the weights optHsPatterns raised every back edge of positive weight by backEdgeBonus (increaseBackEdgeWeight), after a depth-first search for them; under -fcmm-static-pred, on at -O1 and -O2, staticPredCfg then replaces the weights of the branches its heuristics cover with its predictions and estimates frequencies from them. The bonus is now left out there: optHsPatterns takes the back edges to raise, which optimizeCFG gives as none where static prediction follows and as findBackEdges' elsewhere. The bonus counted only at the branches static prediction leaves alone, a heap or stack check's and those whose targets are all back edges, and at a two-way branch back into the procedure's entry, whose weights static prediction starts from, loopInfo counting no edge into the entry a back edge. Leaving it out of those as well changed no code measured. The generated code is the same on every program measured: perf/compiler's T3294, T12707, T783 and T9961 at -O0 and -O, and nofib's programs at -O2 and -O1, whose objects are identical. At -O the stage-1 compiler allocates up to 0.15% less compiling perf/compiler's T3294, T12707, T783 and T9961 (T783); at -O0, where static prediction is off, its allocation moves by 0.006% or less. Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.44% less. Assisted-by: Claude Opus 5.5 - - - - - 33b7340c by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 In sccBlocks, look blocks up in the CFG, not in a set of them sccBlocks, in GHC.CmmToAsm.Reg.Liveness, built a set of every block of the CFG, which holds only reachable blocks, to keep the procedure's blocks that are in it; it now looks each block up in the CFG itself. The generated code is the same. The stage-1 compiler allocates up to 0.24% less compiling perf/compiler's T3294, T12707, T783 and T9961 at -O0 (T783), and up to 0.065% less at -O (T783). Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.11% less. Assisted-by: Claude Opus 5.5 - - - - - fd5fc330 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Inline x86's takeRegRegMoveInstr takeRegRegMoveInstr, which the register allocators and the liveness pass call on every instruction they look for a register-to-register move in, built a Just and a pair for each move it found. Most callers take both apart at once. Inlined, it builds neither where its caller takes them apart. The generated code is the same. The stage-1 compiler allocates up to 0.13% less compiling perf/compiler's T3294, T12707, T783 and T9961 at -O0 (T9961); at -O its allocation moves by 0.011% or less. Assisted-by: Claude Opus 5.5 - - - - - d8e59313 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Swap the registers of a cyclic join fixup where one instruction can Where a jump's target has a recorded assignment, joinToTargets moves the vregs into it, and where the moves form a cycle, handleComponent spilled one source to its stack slot and reloaded it into its destination after the other moves: a store and a load, and a stack slot the vreg may not have had. The Instruction class now has mkRegRegSwapInstr, which gives an instruction that swaps two registers of a format where there is one, and by default Nothing; on x86 and x86-64 it is xchg for the general-purpose registers. handleComponent now swaps a cycle's first source with its destination where it can, so that a cycle of n moves takes n - 1 swaps; it spills as before otherwise, as for floating-point and vector registers. An xchg is two micro-ops on Zen 3, but breaking a cycle through a free register instead, with three movs, ran in as many CPU cycles there and took more instructions (megaparsec's benchmarks 0.114% more instructions at -O2, skipManyTill 2.1% more); breaking floating-point cycles through a free register changed nothing measured, the register cycles it would convert occurring only a few times in all the suites. makeRegMovementGraph's comment that cyclic components seem to occur only very rarely is gone: with master's allocator, orthotope's $w$s$wequalT1 and $w$s$w$ccompare1 break dozens of register cycles through stack slots. The stage-1 compiler's allocation compiling perf/compiler's T3294, T12707, T783 and T9961 moves by 0.001% or less at -O0 and -O. Of nofib's programs only puzzle moves by more than 0.2% in instructions: it runs 0.41% fewer, and 0.7% fewer cycles. containers' benchmarks move by less than 0.1% but for graph bcc.star,n=100, which runs 0.13% fewer; vector's quickhull runs 0.99% fewer at -O1, its other benchmarks moving by 0.10% or less, and megaparsec's run 0.39% fewer (skipManyTill 4.0%, endBy1 1.7%), none more. In megaparsec's count, sepBy and sepEndBy and in vector's quickhull, cycles through stack slots become xchg instructions. Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 08c8cf65 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Store no value into the slot holding it at a join expandNode turned a vreg that is InBoth in the same stack slot at both ends of a join into a store into that slot, beside a register move where the registers differ and alone where they do not, though the slot already holds the value. Such a vreg now needs at most the move. The rule is one first equation of expandNode, taken before master's cases: a destination slot that is the source's holds the value already, so only the destination's register, if any, is written. It replaces master's case of an InBoth source and an InMem destination in one slot and the first guard of its case of an InMem source and an InBoth destination. Measured on x86-64 against its parent, in instructions: the change removes stores and nothing else. vector's benchmarks take 0.28% fewer at -O2 (leaffix 5.26%, rootfix 2.82%); nofib's programs move by less than 0.2% at -O2, -O1 and -O0, and no benchmark of containers, vector or megaparsec rises beyond its noise. The stage-1 compiler's allocation compiling perf/compiler's T3294, T12707, T783 and T9961 and MR 16269's CmmDiamondChain moves by 0.009% at most. Assisted-by: Claude Opus 5.5 - - - - - e7323e24 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Make a join's slot-to-slot move through a free register (ISSUE 27638) A vreg gets a new stack slot where its format outgrows its old one (getStackSlotFor, ISSUE 26668), as a Double's does when x86's broadcast writes its register in place at DoubleX2# (vector_float_broadcast_sse and _avx shuffle the register of a Cmm local). On two paths to a join it can then be in memory only, in a different slot on each, and the join's fixup needs a move from one slot to the other, on which makeMove panicked ("we don't handle mem->mem moves"). makeMove now moves the value through a register free at the jump and in no location of the destination's assignment, at the narrower of the two formats, no more than the source slot holds or the destination slot takes; where no register of that format's class is free and the format is at most 8 bytes wide, through an integer register; otherwise it panics with a message of its own. handleComponent passes the destination's assignment down, and joinToTargets needs FR again, for the free registers. Such a move is in no cycle, no other move writing the slot it reads. The test, T27638, broadcasts a Double in one arm of a case between two C calls; the parent commit's compiler panics compiling it at -O0, -O1 and -O2. Its variants: T27638a broadcasts a Float#; in T27638b the other arm uses the Double again, so that the jump's target expects it both in a register and in a slot, a join the parent commit's allocator does not reach but the series' later allocator does; in T27638c nineteen Doubles are live at the join, so that the move goes through a general-purpose register, and in T27638d thirteen Int#s beside them. The parent commit's compiler panics on T27638a at -O0, -O1 and -O2 and on T27638c and T27638d at -O1 and -O2. With the fix, ISSUE 27638's own reproducer (T27638e, compiled at -O), where move coalescing gives a Double vreg a dying vector's location and format, compiles at -O1 and -O2, as does a generated program that panicked at -O0, its output master's. Cost: compiling perf/compiler's T3294, T12707, T783 and T9961 and MR 16269's CmmDiamondChain at -O0, -O1 and -O2, the stage-1 compiler runs at most 0.006% more instructions (T9961 at -O0) and allocates at most 0.003% more (T9961 at -O2), the assembly the same in every cell; compiling nofib's puzzle, the stage-2 compiler runs up to 0.060% more instructions (at -O0), its allocation moving by 0.002% or less. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear.JoinToTargets allocates 20% more (0.58 against 0.48 GB) and its object is 25% larger, the cost of makeMove's slot-to-slot clause. Assisted-by: Claude Opus 5.5 - - - - - 92521673 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Predict branches into loop heads that only a heap or stack check makes staticBranchPrediction's loop exit heuristic, lehPredicts, says nothing about a branch into a loop head. A heap or stack check that fails calls the garbage collector, which returns to a block that jumps back to the check, and loopInfo counts that cycle as a loop; so in a loop that holds such a check, the check's block is a loop head, and the heuristic said nothing about the test that stays in the loop by branching to it. loopHeads now leaves out a head whose back edges all leave a block of coldBlocks, and the loop levels the heuristic compares count only the loops left: counting the others too would put a block that heads only such a cycle a level deeper than its siblings, so that the heuristic would predict any branch into it. The set is coldBlocks, not checkFailures: static prediction runs after register allocation, so the cycle can close from a block the allocator put after one that follows the failed check, which coldBlocks holds and checkFailures does not. loopInfo no longer counts loop levels (liLevels), which staticBranchPrediction now counts over the loops left, and loopLevels and loopMembers, which had no caller, go, with the import of GHC.Data.Graph.Directed that only loopMembers used. A back edge leaving a continuation that a call returns to as well as the garbage collector counts the same, so a loop closed through such a call loses its head too; telling the two apart moved no figure measured. Where it changes the layout, this saves cycles, not instructions: with the stay side predicted, the layout can let it fall through, a taken jump fewer an iteration, and a conditional jump is one instruction whether taken or not. Before the levels were limited, lookupGE3's loop in containers' lookupge-map took one jump an iteration instead of two, the tag test's jump backward in the layout to the heap check and then one out of the comparison, and GE Twan ran 2% to 11% fewer cycles at no more than 0.03% more instructions; limiting them leaves that loop's jumps as they were. Measured against the parent commit, on x86-64: the instructions of nofib's programs and of containers', vector's and megaparsec's benchmarks move by 0.002% or less in geometric mean, and only intmap fromSet past its bar, 1.0% fewer at -O1. In cycles nofib's programs fell 0.01% in geometric mean with the heads left out and rose 0.3% with the levels limited, single programs moving by up to 12% either way where unchanged code lands elsewhere: gcd's 4.7% rise comes from its bignum code, unchanged but placed 80 bytes later, and hartel/listcopy's 12% from code that a grown function moved. The stage-1 compiler allocates 0.11% less compiling perf/compiler's T783 at -O and 0.060% less compiling T12707, its allocation compiling T3294 and T9961 moving by 0.009% or less; at -O0 its allocation moves by 0.001% or less. Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 981d9202 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 NCG: invert floating-point conditional branches too invertCondBranches turns a block's `jcc next; jmp other` into `jncc other` only where the condition comes from an integer comparison. maybeInvertCond complements the condition on the flags, which nothing between the two jumps changes, so the swapped jumps take the same path for every outcome of a floating-point comparison too, an unordered one included, in each shape genCondBranch' emits for one. Most such pairs nofib's objects keep at -O2 follow a ucomisd and go. mandel2 runs 2.6% fewer instructions and smallpt 0.70% fewer at -O2; no other program whose code changes moves by 0.1%. Assisted-by: Claude Opus 5.5 - - - - - 3c056a57 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Drop the assignments that only a discarded assignment read To move into a merge request of its own, together with "Gather a Cmm sum's literals into one constant, and narrow != as ==", "Address (i << s) + lit on x86 by a scaled index with no base", "Take the constant out of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset into any sum with a constant" and "Assign literals after computed values at the end of a block". Cmm sinking computes liveness once, before its walk, so where the walk discards an assignment that nothing reads, such as a copy, it keeps the assignments that only that one read (ISSUE 8327). Its liveness is now faint: an assignment to a local register that is dead after it uses nothing, so a register that only such assignments read is dead as well, and the walk, which discards every assignment to a dead register, drops a chain of assignments that only one another read in one pass, across blocks and loops. Nothing is folded or inlined again. The liveness is no longer cmmLocalLivenessL's, and sinking checks it as that function does, panicking where a local register is live on entry to the procedure; by the faint liveness, a register that only a discarded assignment reads no longer counts. At -O, hand-written Cmm that reads a register before writing it on some path reaches sinking so: stack layout checks only a procedure declared with a parameter list, and only where it needs the liveness, as at a call, and CmmLint only under -dcmm-lint. Without the check, on a procedure that returns a register written on one branch only, the linear register allocator panicked, and with -fregs-graph the compiler produced code that returns a register nothing wrote. A second sinking pass over every procedure, its liveness recomputed, drops them as well, but in a trial it made the compiler allocate 60% more compiling perf/compiler's T3294 at -O, and its constant folding, which in that trial rewrote (a - b) + c to a + (c - b) whatever b and c were, cost containers' elemAt benchmarks up to 2.4% more instructions. Recomputing liveness until no assignment is dead drops them too, but takes a pass for each link of a chain of assignments each read only by the next: on a procedure with a chain of 400, the compiler allocated 9.2 times what master's does. The test, T8327, is a Cmm loop that assigns a constant read only by a copy that nothing reads; the constant must not appear in its Cmm. With the parent commit's compiler it does. Measured against the parent commit, on x86-64: vector's benchmarks at -O1 run 2.1% fewer instructions (sum[base] 14.3%, map[base] 9.1%, spectral 5.0%, generateIO 4.0%), none more by over 0.003%; in sum[base]'s loop, the address of the SPEC token that vector's stream fusion passes from one iteration to the next was loaded at each iteration, read only by an assignment that sinking discarded. At -O2 none moves by more than 0.005%, and those that move most have the same code. containers' benchmarks at -O2 run up to 9.5% fewer (nubOrd noFusion_repeat 9.5%, issue1202_repeat 4.7%, set alterF:insert:present 2.9%, lookupge-map GE split 0.61%), none more; at -O1 only Data.Sequence's code changes, and no benchmark moves beyond its noise. megaparsec's benchmarks at -O2 run up to 1.0% fewer (skipManyTill 1.0%, manyTill 0.74%), none more, and at -O1 none moves. Of nofib's programs only rewrite's objects change, and no program moves by as much as 0.2%; fannkuch-redux does not change. The stage-1 compiler allocates 0.085% less compiling perf/compiler's T3294 at -O and at -O2, 0.097% and 0.085% less compiling T12707, 0.044% less compiling T783 and 0.083% to 0.085% less compiling MR 16269's CmmDiamondChain at -O1 and -O2; at -O0, and compiling T9961, within 0.007% of what it allocates at the parent commit. Compiling nofib's puzzle at -O2, the stage-2 compiler allocates 0.094% less. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 95d5e282 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Keep Sp put across loops and tag tests in stack layout To move into a merge request of its own, together with "Put a block's reloads after its leading unwind in stack layout". Stack layout gives a block the stack map of the first of its predecessors it visits, and every later edge into the block gets a fixup. It sets a diamond's frame (Note [diamond proc point]) up before the tag test, trimmed to the variables live in the continuation, and the continuation reloads them all, on the evaluated path too. So in a loop whose body evaluates a variable, every iteration moves Sp twice and stores the loop's invariants again, and where the variable was evaluated already, it reloads registers that still hold their values. These changes to GHC.Cmm.LayoutStack keep Sp and the slots put: * a loop head takes the stack map its back edges have in common, by a second layout run where that pays, and the edge into the loop pays the difference once (Note [Loop head stack maps]); a back edge reached only through unlikely branches proposes nothing, and a head every cycle through which makes a non-tail call to its own procedure is left alone, its loop turning about once an entry (nofib's tak, containers' foldrWithKey'); * a loop head that takes no such map, its back edges differing in depth or needing no fixup, gets in the second run the depth of the deepest continuation in its loop, with the loop's invariants in the slots that continuation's frame gives them: a call returning into the loop keeps that depth, where it moved Sp twice an iteration, down at the call and up at the fixup on the edge where its return path joins a path that made no call, and the edge into the loop pays the Sp move and the invariants' stores once (Note [Reserved frames in loops]), and where the second run seeds both kinds of head and its seeds do not all hold, a third run seeds only the heads that take a common stack map; * the continuation becomes its reloads and a jump to its body, which the evaluated path jumps to directly, where proc points are not split and the reloads this adds at earlier proc points stay at most two a diamond, or else for the diamonds whose tag test follows no proc point whose reloads grow (Note [Tagged path skips the reloads]); on a loop holding at most sixteen diamonds' continuations the body takes every variable in its register but one live across an inner loop that does not read it, and elsewhere only those stored on the call's edge, reloading the rest itself where they are used; * the return address is stored on the call's edge only, where the call is the only block returning to the continuation; * a variable that at most one later call needs in a slot is stored on the call's edge only too, that later call storing it on its own path (Note [Tagged path skips the stores]); * a diamond's frame keeps the stack's depth, its dead slots left as holes (Note [Diamond frames keep their depth]); * the frame a call into a diamond's continuation pushes is trimmed to its live variables after layout, by a pass of its own, where, among other conditions, proc points are not split and either the procedure is called by a thunk of its Cmm group, as a lazy list's producer is by the thunk of the list's tail, or the holes are at least half the live words and the procedure is a thunk or the continuation is on no loop: the call can evaluate a thunk that leads back to such a frame, and each level of the recursion would hold the holes (nofib's primes and multiplier); each call returning there moves Sp up to the trimmed frame, the continuation moves it back down, and the tagged path moves it nowhere (the same Note). This fixes ISSUE 27991 for its example, whose loop stores nothing on the stack at its iterations, and ISSUE 8905 in part: where a loop's body evaluates a variable, the call's frame is set up on the call's path only in the cases above, the others keeping the stores and reloads it describes. The reservation leaves these cases out, each having paid more than it saved: * a continuation reached only through unlikely branches, which reserves nothing: a heap check's GC call returns into many a loop that makes no other call, whose every entry and exit would pay for a frame only that rare path uses (megaparsec's word32be, containers' lookupGE). A block is reached so where every edge into it is the unlikely side of a branch, the side a branch on a literal never takes, or leaves another such block, and rts/include/Cmm.h marks MAYBE_GC's test unlikely, so that the primops whose `again: MAYBE_GC(again)` retries through the GC call, newArray# and newAlignedPinnedByteArray# among them, set up no frame on their fast path; * a loop that only permutes the variables live at its head, as integerAdd's swap of its arguments, which turns a few times an entry; * a loop making a non-tail call to its own procedure, each level of the recursion then holding the reserved frame, a stack the garbage collector scans (containers' foldl' over a line-shaped tree); * a loop holding a head seeded from its back edges, whose seed expects its variables in other slots than the reserved frame gives them (nofib's puzzle, six register swaps at a join). A variable that the continuation's code saves at the first call it reaches without a conditional branch, within eight blocks, not redefining it on the way, is still stored before the test, whether or not that code reads it: the tagged path would store it there anyway, and the call's path would reload it at the continuation to store it again (nofib's fasta, and A2T's zipWith5A and broadcast over small arrays). In a procedure that makes a non-tail call of itself, and for a diamond on a cycle of blocks, cold ones left out, that makes no non-tail call into the procedure's recursion (its strongly connected component in its Cmm group's call graph, computed once a group in GHC.Cmm.Pipeline), those stores all stay only where the call's frame, set up there, is no deeper with them all, and otherwise each only where that frame has its variable in the slot the diamond's frame gives it, in the call's own slot order or, where the frame is then no deeper and its youngest slot of a variable that one or more later non-tail calls of the procedure itself need, and of one that two or more need, lies no younger than in that order, in the plain one: otherwise the slot would deepen every level of the recursion (containers' PostOrder folds), or a loop's seeded frame would be set up and dropped every iteration (containers' intset insert and sequence update.10). tagSkip, which splits the continuations, checks the limit of two reloads a diamond first against a bound read off the graph, each diamond's variables taken in registers times the proc points whose regions hold its tag test, and runs its analyses only where the bound exceeds the limit; there it takes each block's live-in from the liveness analysis, computing it only at a proc point that is no split continuation, its loop rule (across) tests only the frame's variables, and the continuations on one loop share each block's successors in it. laterSearch, which counts the later calls that need a variable in a slot, searches only as far as each query needs, over Steps that link each block to its successors' so that a search looks up only its first block; across numbers each loop's blocks, and liftFrames and tagSkip no longer walk every frame. Layout's search for back edges, and has_loop, look for a back edge before testing the cold blocks, so that the cold blocks are computed only where one is found; the strongly connected components, shared by loopHeadSeeds and reservedSeeds, are computed only where a loop head passes loopHeadSeeds' other tests or, for reservedSeeds, an edge enters a proc point that is not cold; liftFrames tests a frame against its size rule before its loop; and a block's middle nodes are copied by (++) only where something is appended. In GHC.Cmm.Info.Build, cafAnal takes a jump into a split body as a reference to its continuation's info label: otherwise each block's set gathered every later continuation, at a cost growing with the square of a procedure's chain of evaluations. None of this changes the generated code. Layout joins the block on a call's edge to the call's block where it ends, where the call has no other way in and the procedure has a diamond: unjoined, each tag test adds a block to the maps the later passes keep of blocks, and at -O0, where no later pass joins blocks, a jump. A heap or stack check's GC call returns to a continuation that reloads the variables and jumps back to the check. Where a split body jumps to that check too, holding the variables in other registers than the reloads give them, the allocator would fix the check's registers from the retry and permute them on the hot path at every pass; so, where the block the check's passing branch leads to ends in a jump, the retry jumps to a copy of the check, whose passing branch leads to a copy of that block, and the hot check keeps one way in (Note [Retries copy their checks]; A2T's rotate.inner over large dense Storable arrays, which permuted its registers by a cycle of xchg at each allocating check). A change to GHC.CmmToAsm.BlockLayout goes with these: * with the latch's fixup gone, a loop's exit can have the latch's conditional edge and another block's unconditional one as direct predecessors of near equal weight; buildChains, dropping the latch's edge back into the loop as closing a cycle, left the latch's other edge at its weight, so the other block fell into the exit and the latch paid a jump an iteration (ISSUE 27799's reproducer, with or without -fobject-determinism); where buildChains drops a conditional edge from a chain's end into that chain's start, the branch's other edge, if lighter and its target, unplaced or starting a chain, has no info table, now takes the dropped edge's weight (Note [Latch edges after a cycle]). The tests StackLayoutTagLoop, a loop evaluating each element in a diamond, and StackLayoutCallLoop, a loop calling a function on one of its paths, in codeGen/should_compile check the assembly for a return address stored below Sp, which each stored before this commit. A third, T27991, the example of ISSUE 27991, searches the assembly for any movq of a register to an address off %rbp, Sp's register: with the parent commit's compiler its loop stores two at every iteration. Taking the variables in registers at the join is a trade: containers' set foldMap_traverseSum takes 3.85% more instructions at -O1, and at -O2 map's fromSetA inner rows 0.39% to 0.45% more and intmap's Strict fromSetA inner row 0.32% more (0.11% at -O1), the split continuation's body moving its variables between registers at the join where the parent's code used a memory operand; and orthotope's A2T benchmark's window.zero, summed over large arrays, takes 5.04% more with boxed elements and 3.37% more with Storable and Unboxed ones, its sumView loading five to eight frame slots into registers on the path every iteration takes; where a loop's elements take the call path, the split continuation reloads the variables its body takes in registers at every continuation, where the parent reloaded each at its use, as in A2T's zipWith5A and concatOuter.map over small arrays, window over large runs of Unboxed elements and rotate.inner over large dense Storable arrays. The trade's toggle is Note [Tagged path skips the reloads]: the body reading the variables from their slots instead makes nofib's compress take 6.8% more instructions and queens 6.1% more. Taking them in registers only on loops holding at most sixteen continuations is a trade too: nofib's para takes 0.27% more instructions at -O1, by one loop holding more, where taking them in registers saves reloads and register moves at -O1 and costs reloads at -O2, nearly every diamond there taking its call path. Lifting the limit reverts it, but makes para take 0.50% more at -O2 and puzzle 4.38% more at -O1 and 2.23% more at -O2. Storing on the call's edge only a variable that one later call needs is a trade: at -O0 nofib's tak, mandel2, life, rfib, fasta and others take more instructions, at -O1 multiplier, and at -O2 atom, ansi and life, the path through a diamond's call paying a jump to the split body and a register move more; the diamonds that lose and those that gain differ only in their callers' arguments, which lie outside the procedure that stack layout processes. In containers' graph benchmarks the first of dfs's two calls stores on its edge a variable the second call does not need, and line inputs gain by the smaller first frame, dfs.line,n=1000000 24% fewer bytes at -O2 and -O1. Storing every variable before the test instead makes nofib's programs take 0.91% and 0.98% more instructions and containers' benchmarks 2.3% and 2.7% more, at -O2 and -O1, and megaparsec's 3.4% more at -O2. Stored in the older of two fresh slots, dfs's variable would leave a hole in the second call's frame, a word a level of the recursion, and make star inputs allocate a stack chunk more each time those words add up to one. So for the frame of a non-tail call of the procedure itself, in a procedure that loops, the variables later such calls need take the older slots, where the frame would otherwise put one that none of them needs in a slot older than one that one needs, and the next such call's frame, once the others have died, trims from the young end. This is a trade: against the commit without it, at -O2 and on graphs of a million nodes, dfs.star allocates 10.2% fewer bytes and scc.star and scc.line 5.4% fewer, and the depth-first searches over stars, and scc and stronglyConnCompR over lines, take 0.5% to 1.65% fewer instructions, while containers' other Data.Graph benchmarks take up to 0.56% more, the most on graphs of a hundred nodes, the second of dfs's calls moving Sp up to its trimmed frame where the hole kept it put; and the compiler allocates 0.14% more compiling T9961 at -O0. Ordering the slots of every frame instead costs an Sp move at each trimmed call of other recursions, containers' foldMap_elem 1.2% more instructions and nofib's binary-trees 0.76% more, and ordering every frame of a procedure that calls itself and loops costs Sp moves at each node of Data.Tree's folds over a node's children, Foldable1's foldMap1 over a line 6.8% more instructions. Reserving a loop's frame is a trade: nofib's boyer2 takes 0.21% more instructions, a loop's entry moving Sp and shuffling registers at each iteration for a call path run less than half as often, and containers' tree PostOrder.Foldable maximum 1.35% more at n=1000 and 0.39% more at n=1000000; a further left-out case, for loops calling a procedure private to the module, reverts them, but also gives back the gains of nofib's sched (0.9%), transform (0.4%) and parstof (0.3%). megaparsec's reachOffset-1000-1000 takes 1758 instructions with or without that case, a few more than without the reservation: the reservation's own trade. Giving a loop head the stack map its back edges have in common is a trade too: a loop whose head is its exit test and that runs no trip or one moves Sp down at its entry and up at its exit, where the parent moved it at neither, so that in orthotope's A2T benchmark Ranked's and Dynamic's scalar strided cells over Storable and Unboxed elements take 2 and 3 instructions a call more, the generate.scalar strided cells over Unboxed elements 2 to 6 more and Shaped's over Storable and boxed ones 1 more, and Shaped's empty toVector and toUnorderedVectorT cells 3 to 4 more; leaving the loop-head maps out reverts these with the gain on ISSUE 27991's example. Copying such a head's exit test onto the edges into its loop, where its map holds without the copy and the loop's exit reaches no call, takes these back, but makes containers' intset fromAscList take 20% more instructions, in the garbage collector, and map fromDescListWithKey 3.4% more at -O1. Taking a block as cold where every edge into it is cold, rather than one that an unlikely branch alone enters, is a trade: containers' graphFromEdges takes up to 0.54% more instructions and nofib's awards 0.55% more at -O2 and -O1, where the wider rule changes the code of GHC.Internal.Data.OldList and of awards' QSort, and containers' set foldMap_traverseSum 0.77% fewer at -O2; the narrower rule leaves a frame on the primops that retry through MAYBE_GC. Code grows: nofib's objects take 1.3% more bytes at -O2 and 1.2% at -O1 (0.13% at -O0), as the split continuations' bodies move their variables into registers at the joins and reload them at the continuations, and each trimmed frame's call moves Sp up and its continuation moves it back down. Not trimming takes back about a quarter of that and costs primes' and multiplier's stack; the trade's toggle, the bodies reading their variables from their slots, takes back the moves and reloads only by storing on both paths, which makes code larger still. The compile cost is that of these analyses and of the larger code: against the parent commit the stage-1 compiler allocates 1.6% more compiling perf/compiler's T12707 at -O0 (1.1% and 1.0% at -O and -O2), 0.87% more compiling T9961 and 0.65% more compiling T783 at -O0, and 1.1% less compiling T3294 at -O0; over nofib's compilations the stage-2 compiler allocates 1.9%, 1.7% and 0.86% more in geometric mean at -O2, -O1 and -O0. Compiling MR 16269's CmmDiamondChain, the stage-1 compiler allocates up to 0.018% less and runs 0.67% to 0.81% fewer instructions. T12707's is a trade: of the 1.1% more instructions the stage-1 compiler runs compiling it at -O0, turning tagSkip and liftFrames off takes back about 0.6 points and gives up what they gain, and the rest is layout's work a diamond and that of the passes after it on the code layout changes; nofib's compile cost, at -O2 and puzzle's the most (the stage-2 compiler allocating 9.1% more compiling puzzle at -O2), goes with the size trade, the passes after layout working on the larger code. Stack layout's local liveness is an LRegSet, as in master's cmmLocalLivenessL, and the Data.Set form goes: GHC.Cmm.Liveness's cmmLocalLiveness, noLiveOnEntry and the SPECIALIZE pragmas of liveLattice and xferLive at LocalReg are deleted, CmmLocalLive becomes LRegSet, and liveLatticeL tests a change by isSubsetOfUniqueSet rather than by the joined set's size; GHC.Cmm.Lint calls cmmLocalLivenessL; insertReloadsAsNeeded runs over LRegSet; and setupStackFrame takes the variables live at a proc point as a BlockId -> LocalRegSet, the Data.Sets built once at each proc point from a table, by unique, of the defined variables live at one. This is a trade: against the same tree with the Data.Set form, the compiler runs 0.138% more instructions and allocates 0.017% more compiling T783 at -O0, and 0.025% and 0.037% more compiling puzzle at -O0 (T783's in Word64Set's operations on its small sets and the table's walk; puzzle's instructions in the table, its walk over every node's definitions and the Data.Sets built from it, the set operations themselves running fewer, and puzzle's allocation in Word64Set's insertions and deletions), and less in every other compilation measured: T3294 at -O0 2.31% fewer instructions and 1.79% less allocation, CmmDiamondChain at -O0 1.17% and 0.51%, puzzle at -O2 0.18% fewer instructions. Keeping the Data.Set form reverts both. Where the second run's seeds do not all hold, or the third's where that runs, the heads whose seeds held run again with theirs alone (Note [Loop head stack maps]). This is a trade: the run costs the compiler 0.016% more instructions and 0.020% more allocation compiling puzzle at -O2, and nothing in the other compilations measured, and makes nofib's gen_regexps take 9.05% fewer instructions at -O2 and -O1, two Sp moves fewer a character of its inner walk over each string and one more a string, cacheprof 0.38% fewer, containers' transposeG 2.9% to 3.4% fewer and megaparsec's scientific 2.5% to 3.9% fewer at -O2. Keeping the first run at once reverts both. In GHC.StgToCmm.Utils, emitMultiAssign, master's code, no longer assigns a variable to itself, as a self-recursive tail call or a jump to a let-no-escape binding passing an argument unchanged did: layout takes an assignment to a variable as leaving the variable's slot stale, so that the next call stored it again. This is a trade: the compiler runs 0.151% and 0.156% fewer instructions compiling T783 at -O and -O2, and 0.022% and 0.023% more compiling T12707 at -O and -O2, where it allocates 0.026% and 0.027% more, in maps and sets keyed by uniques, which shift once those assignments are gone; the generated code differs only in its labels. Emitting the assignments again, with layout exempting them, reverts both. Measured against the parent commit, on x86-64, in instructions: nofib's programs take 3.7% fewer at -O2, 4.5% at -O1 and 0.72% at -O0 in geometric mean (gen_regexps 34%, queens 24% and bspt 20% at -O2, k-nucleotide 40% at -O1), and some take more: at -O0 tak 1.45%, life 1.31%, mandel2 1.31%, rfib 1.02%, nucleic2 0.75%, parstof 0.68%, kahan 0.61%, digits-of-e1 0.58%, fasta 0.48%, fulsom 0.42%, atom 0.26% and solid 0.23%, at -O1 life 1.32%, sphere 0.67%, ansi 0.36%, multiplier 0.33% and atom 0.31%, and at -O2 life 1.32%, ansi 0.33% and atom 0.31%. containers' benchmarks take 6.1% fewer at -O2 and 6.6% at -O1 (graph dfs.maxDAG,n=15 36%), and more in intmap's cps folds, 0.93% to 1.01% at -O2 and -O1, set foldMap_traverseSum and the fromSetA rows above, and sequence fromFunction.ix10000/5000, 0.82% at -O1. megaparsec's take 6.7% fewer at -O2 and 4.6% at -O1 (reachOffsetNoLine 23% at -O2, string' 13% at -O1), reachOffset-1000-1000 1.1% more at -O2 and 1.05% at -O1; vector's 4.3% fewer at -O2 and 10.5% at -O1 (minimumOn 31%), none more. Of the cells of A2T's sample that move by 0.2% or more, all take fewer (toList and toVector over small dense boxed arrays 28%) but the scalar and generate.scalar strided cells above. No nofib program's allocation moves; containers' set alterF:insert:absent allocates 3.11% more at -O2 and -O1, a stack chunk, and intmap difference-common_nn_swap a stack chunk more at -O2, where difference-common_sn_swap allocates one fewer. Compiled by the stage-1 compiler, as when building stage 2, GHC.Cmm.LayoutStack allocates 4.7 times as much (8.53 against 1.82 GB), GHC.Cmm.Pipeline 74% more (0.81 against 0.47 GB) and GHC.Cmm.Sink 13% more (2.13 against 1.88 GB). The compile cost grows with a program's size: compiling the battery's scaling programs calls, lists, deadchain and allocs at -O1, the stage-2 compiler allocates 2.0% to 5.7%, 9.1% to 13.5%, 1.0% to 12% and 1.8% to 5.2% more, from N = 50 to N = 400. Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 57846e41 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Load a field again after a call from its saved constructor To move into a merge request of its own, on top of that of "Keep Sp put across loops and tag tests in stack layout". This commit lies outside the series' core, GHC.CmmToAsm, as a named exception: it changes stack layout, GHC.Cmm.LayoutStack, and StgToCmm, which records for it the registers a case alternative loads its constructor's fields into. A case alternative loads the fields of its constructor where it starts, so a field used only after a call is loaded before the call and saved across it (ISSUE 20334). Saving the constructor in place of its fields could keep dead fields alive (ISSUE 20333), but where the constructor's variable is saved across the call anyway, its slot keeps them alive already. There stack layout now saves the field nowhere and loads it from the constructor after the call, where the variable is reloaded, or, in a body split off a tag test's continuation, after the test, on the paths that use it. This runs only under -fcmm-sink, without which the load before the call would stay. StgToCmm records the registers of each case alternative that loads every field of its constructor, two or more (a CgConFields statement in the code, which emitProc collects into CmmStackInfo's con_fields while flattening the code), and two rules decide the proc points where a field is live. Where its constructor's variable c is live, a field is left out at every such point or at none: at each where the field is wanted after the call (used before the next proc point, saved at one, or the region larger than the sixteen blocks walked), c must be used there too. Where c is dead, the decision is made per call: c is saved in place of the fields where every register of their alternative is live, two or more of them are saved across no call where only some of them are live, nor across a diamond's call whose body uses some of them, and one of them is live at some proc point that is neither the procedure's entry nor a continuation only heap checks' calls to the collector return to, and nowhere else, so that it keeps no dead field alive, its store replaces two or more, and a diamond's tagged path keeps the fields in registers. A function closure loads its free variables where its code starts, and their registers are listed as an alternative's too, so that the closure is saved in their place across a call after which they are live and it is dead (ISSUE 20333), and across a diamond's call. Against its parent, nofib's puzzle runs 5.7% and mate 2.4% fewer instructions at -O1, and no program runs 0.2% more at -O1 or -O2; containers' IntMap symmetricDifference benchmarks run up to 9.0% fewer at -O1 and the map and set cpsOneShotSum folds 2.6% to 4.0% fewer at -O2 and -O1; T20333's code at -O has half as many stores of a double to the stack; and the stage-2 compiler takes 1.2% fewer instructions and 0.43% less allocation compiling puzzle at -O1, and 0.14% fewer instructions and 0.17% more allocation at -O2, its code changed at both. Past their bars upward: containers' intmap union-disj_nn and union-disj_nn_swap at -O1, 111% and 104% more instructions, allocating 33496 bytes against 728, a stack chunk more (on an earlier form of the series the benchmark's warm-up call stayed within the initial stack and the measured call overflowed it, and with a larger initial stack they ran fewer instructions and allocated the same), and the rows allocating one stack chunk more, intmap difference-common_nn_swap at -O1 and symmetricDifference-mix_ns and mix_sn_swap and sequence splitAt/append.100 at -O2; intmap restrictKeys:random, 0.47% more instructions at -O2, graphFromEdges.line,n=100, 0.18% and 0.14% more at -O2 and -O1, and the intmap and intset symmetricDifference-disj_nn_swap rows, two instructions more at -O2; megaparsec's scientific benchmarks, 0.17% to 0.24% more at -O2 and 0.59% to 0.86% more at -O1, and reachOffsetNoLine 0.47% more at -O1; vector's map[lens], 1.1% more at -O2 and -O1; and the reshape cells of orthotope's A2T sample, four instructions a call more (0.31% to 0.60%), and its Storable and Unboxed stretchOuter cells one more (0.25%). Stack layout follows the alternatives in one walk over the proc points, leaving one once fewer than two of its registers remain to be saved in place of its constructor's variable: over every alternative at every proc point the compiler allocated 0.49% more compiling Data.Colour.Names at -O2, whose one function closure's free variables are each live up to one call of a chain, and it now allocates within 0.03% of what the series' end allocates without this commit. Saving the closure holds it from its assignment to the call beside the free variables used on the way, so where the blocks reached from its assignment without passing a proc point hold a loop, on the way to the call or not, it is saved in their place only where one of them is used in none of those blocks that assign the closure or start with it dead: in spectral-norm's timesAtAv, whose loops use two of its closure's four free variables and a call after them the other two, the closure otherwise held one register more in the loops and ran 5.9% more instructions. Without a loop the register held more costs one spill and reload at most, and saving the closure in place of k free variables saves k - 1 stores for one load more. A constructor's alternative keeps the rule above: declining where a loop before the call used three of four fields cost two instructions a call, and in loop-free code declining moved nofib's fish by +0.28%, its gains in multiplier and boyer being those of the rule for heap checks below. The test costs instructions compiling puzzle at -O2, in stack layout's own walks. At a diamond, saving the closure in place of k free variables saves the tagged path k loads and k stores for a move of the closure out of R1 and its store, and costs its reload and the k loads from it, which fold into their uses as reloads from the stack do, where a heap check follows only if they go below it (below): 2k - 3 instructions fewer, less one for each used after a store to the heap, which its load does not pass, and 3 - k more where they stay above the check. Where none of an alternative's registers is live at a proc point that is neither the procedure's entry nor a continuation only heap checks' calls to the collector return to, they are saved across those calls and its constructor's variable is not: holding the variable to the check costs the path passing it a register, nofib's boyer copying it to another one, and saving it in their place saves stores only on the path to the collector. Against this commit without the rule, nofib's multiplier runs 0.26% and boyer 0.21% fewer instructions at -O2, 0.22% and 0.21% at -O1, and no program runs 0.2% more at -O2, -O1 or -O0, where no object changes; megaparsec's benchmarks run 0.30% fewer at -O2 and 0.53% at -O1 by their geometric mean, up to 3.0% fewer, and none more; no containers benchmark runs 0.1% more and no vector benchmark moves by 0.05%; and the compiler's allocation moves by under 0.01% compiling T3294, T12707, T783, T9961 and CmmDiamondChain, and rises by 0.1% on no module of containers, vector or megaparsec. Where a proc point, or a body split off one, ends in a heap check, the block the check passes to, entered from it alone, loads the fields loaded again there that neither the check's block nor the collector's call uses or assigns, below the check, where they fold into their uses unless used after a store to the heap; and a function closure of two free variables, not only three or more, is saved in their place across a diamond's call. Against this commit without both, nofib's sphere runs 1.00% fewer instructions at -O2, sched 0.41%, clausify 0.35% and treejoin 0.27%, and sched 0.51%, compress2 0.40% and clausify 0.34% at -O1, and no program whose objects change runs 0.2% more at -O2, -O1 or -O0, where no object changes; containers' IntMap cps folds run 1.9% to 2.0% fewer, two instructions an element, one of them a register move, and no containers benchmark runs 0.1% more; megaparsec's choice benchmarks run 3.0% to 3.1% fewer at -O2 and 2.4% at -O1, count 2.0% to 2.1% fewer at both and skipManyTill 0.51% fewer at -O1, 0.19% and 0.20% fewer by the geometric mean; no vector benchmark moves by 0.05%; no cell of orthotope's A2T sample runs 0.2% more, and twelve of its slice cells run 0.21% to 0.25% fewer, two instructions a call; and the compiler's instructions and allocation move by under 0.001% compiling T3294, T12707, T783, T9961 and CmmDiamondChain. The loads below the check cost megaparsec's scientific benchmarks 0.36% to 0.46% more instructions at -O2, two register moves a digit, and sepEndBy 0.26% more at -O1, one move at every second character: in sepEndBy the continuation's reloads from the stack, sunk into that block, come before the fields' loads, and the linear allocator's first free register for one of them is then not the one a tail call's argument wants. That is a trade: loading the fields above the check takes these rises back with nofib's gains, choice's and skipManyTill's, and makes saving the closures of two free variables cost set's traverseSum folds 0.6% to 0.7% more instructions, one an element. Measured on an earlier form of the series, against that form's tip, with an earlier form of this change: containers' benchmarks ran 0.58% fewer instructions at -O2 and 0.77% fewer at -O1, the rows that rose, in instructions or by one stack chunk's allocation, rising no more under a larger initial stack; and in orthotope's A2T benchmark every rotate cell allocated the same and none ran more than 0.1 instructions a call more, rotating an empty dense Storable array taking 620.78 instead of 626.76. The test T20334 greps the assembly of three functions for Doubles stored on the stack: the reproducer posted on ISSUE 20334, a variant whose call is to length, and one whose constructor is dead across the calls, saved in place of its fields. Of the 11 the parent commit stores, only the three of V's constructor function's entry to the GC remain. T20333 greps the same in ISSUE 20333's example, in Double#s, and in a variant whose closure's free variables are used after a call: of the 16 the parent commit stores, only the 8 of foo's and bar's entry to the GC remain. T20333b and T20333c grep the offsets of the stores below Sp: where a function closure's four free variables are used in both arms of a branch before a call and after it, the closure's entry stores one value on each path where the parent commit's code stores four; and where a case alternative uses its constructor's four fields across a loop and a call, the parent commit's two stores below Sp in its function go. Measured with stage-1 compilers against the parent commit, the compiler runs 0.19% more instructions and allocates 0.10% more compiling perf/compiler's T12707 at -O, whose assembly changes, and 0.17% and 0.090% more at -O2; it runs 0.27% more instructions and allocates 0.052% and 0.051% more compiling T3294 at -O and -O2, and runs 0.086% more instructions compiling MR 16269's CmmDiamondChain at -O1 and -O2, their assembly unchanged; and for T783 and T9961 at -O and -O2, and for CmmDiamondChain's allocation, it changes by 0.028% or less. Compiled by the stage-1 compiler, as when building stage 2, GHC.Cmm.LayoutStack allocates 29% more (11.02 against 8.53 GB). The stage-2 compiler runs 0.14% fewer instructions and allocates 0.17% more compiling nofib's puzzle at -O2, whose assembly changes, and allocates 0.056% more in total compiling nofib's programs at -O1, 0.022% by the geometric mean, sphere 0.22%, simple 0.15%, anna 0.13%, transform 0.12% and clausify 0.072%. Collecting the alternatives' registers while flattening the code and deciding once a procedure whether any field is loaded again took 0.065 points off T12707's instructions at -O. Of what remains, callgrind put, on an earlier form of this change, most of T12707's rise in instructions at -O and of puzzle's at -O2 in the analysis: in finding, at each proc point, the listed alternatives with a register live there whose constructor's variable is dead, at the proc points where a field's constructor's variable is live too, the walks over their first blocks included, and, for T12707, in the walk over the loads with each proc point's liveness; and some of T12707's rise outside stack layout and the code's flattening, Word64Map's inserts and the updates of thunks the most. At -O0, where the analysis is off and the assembly the same, the compiler runs 0.062% fewer instructions compiling T9961, 0.036% fewer for T12707, 0.019% fewer for T783 and 0.019% fewer for CmmDiamondChain, but 0.002% more for T3294, and allocates 0.025% to 0.099% less. Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 63b10ed3 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Jump conditionally to a likely false comparison's false target genCondBranch jumps to the true target conditionally and to the false one after, and ignores cml_likely. Where the layout makes either target a fall-through, invertCondBranches and dropJumps leave one conditional jump whichever order it emits; where neither jump falls through, the conditional jump is the shorter way to its target, so invertCondBranches now swaps the two jumps of an integer comparison likely false whose true target does not come next. After layout rather than before genCondBranch: swapped there, every heap and stack check's jumps were swapped and swapped back by invertCondBranches, costing up to 0.29% more instructions compiling at -O0. invert examines a block's last two instructions once and chooses between the old rule and the new one. Measured on x86-64 against its parent, in instructions: containers' IntMap fromSet and fromSetA rows take 0.32% to 0.46% fewer at -O2 and fromSet 0.36% fewer at -O1, beyond the leftover jump "Drop jumps over blocks dropJumps empties" removes there; no benchmark rises beyond its noise, and the stage-1 compiler's allocation moves by 0.043% or less compiling each of perf/compiler's T3294, T12707, T783 and T9961 and MR 16269's CmmDiamondChain, at every level measured. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - b3a44650 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Add an estimate of block frequencies for the linear allocator blockFrequencies in GHC.CmmToAsm.CFG makes mkGlobalWeights' estimate of how often each block runs, for the linear allocator, from the native CFG before allocation: static prediction's edge probabilities (the two-way rule factored out of staticBranchPrediction as predictBranch, shared, given the procedure's tagRegisters as the layout's estimate is) and calcFreqs' fixpoint, with loops found by one depth-first search and the whole computation in two arrays. A later commit passes it to the linear allocator. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.CFG allocates 20% more (4.17 against 3.47 GB). Assisted-by: Claude Opus 5.5 - - - - - 23477bfc by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Allocate hotter SCCs first, the procedure's first block before them Where block frequencies are estimated, linearRA_SCCs allocates the SCCs hotter first among those it can allocate (hotFirst, an order computed before allocation from the jumps), the procedure's first block before any other and another entry as hot as the hottest of itself and the blocks it jumps to, an SCC's heat compared in factors of 1.2 with ties to the earlier in dependency order, and sets aside an entry other than the first block while a block it jumps to, not yet reached, runs more than 1.2 times as often as the entry; where nothing can be allocated, the entry set aside that the estimate calls hottest goes next. This replaces the deferral of the blocks the garbage collector returns to and of a continuation entering a call-free loop, which stay where there is no estimate: on x86-64 without -fcmm-static-pred, as at -O0, and on other targets, where allocCold is empty and only the continuation's deferral stays. The first block first keeps a loop calling itself on the argument registers (Data.Tree's and Data.Map's folds); the factor leaves to dependency order what static prediction's 50/50 on some tag tests makes of the paths around an evaluation (Data.IntSet's fromAscList loop); the hottest entry set aside first gives a join of two continuations, both waiting, the hotter's registers (Data.IntMap's mapKeysMonotonic and Data.IntSet's fromList at -O1); an entry ranked by its hottest jump target, not above every other SCC, keeps a continuation before the path into the block it jumps to (nofib's fannkuch-redux at -O1) without putting colder continuations before a hotter one (Data.IntSet's mapMonotonic at -O2). hotFirst is NOINLINE, so that its local thunks are not allocated for every procedure at -O0, where it is not called. CmmToAsm passes Linear.regAlloc the estimate of block frequencies from a given entry where static prediction is on (-fcmm-static-pred), as for the layout's estimate, and regAlloc computes it from the procedure's first block. Within a cyclic SCC that holds a block whose first jump target in it and another differ in estimate by a factor of 1.2, and that is entered at one block, reached from outside it or an entry, hotFirst gives the blocks hottest first (hotOrder), each block's jump targets in the SCC reached as it goes, so that the hotter side of the branch fixes its join's registers and the colder side pays the moves. Entered at more blocks, its joins also meet registers fixed apart from the order, an outside predecessor's at a block reached from outside and none at an entry, and the order would rank such blocks by an entry's heat, the estimate's guess for the call or evaluation returning to it: so ordered, nofib's puzzle at -O2, whose loops are entered at many blocks, ran no faster, and the compiler ran 0.15% more instructions compiling it. Measured with the order placed at the end of the series, against that end, in instructions: megaparsec's skipManyTill, manyTill and endBy take fewer at -O2, and nofib's wheel-sieve1 fewer at -O2 and -O1, wheel-sieve2 too, and k-nucleotide at -O2, and no benchmark takes more beyond its noise; no compile-cost cell moves beyond its noise. Measured on x86-64 against its parent, in instructions by the geometric mean: nofib's programs take 0.28% fewer at -O2, 0.30% at -O1 and 0.54% at -O0, through the libraries' code, and at -O2 and -O1 containers' benchmarks 0.47% and 0.53% fewer, vector's 0.075% and 0.58% and megaparsec's 0.44% and 0.17%. The order is a trade, its toggle the order itself (hotFirst's guard in linearRA_SCCs). In loops closed through a call, which the estimate rates at a trip multiplier far below the run's, containers' map fromList-distinctAsc:fusion takes 2.4% more, set fromDistinctDescList:fusion 2.0% more and intset fromRange:small 1.4% more at -O2, and nofib's scs 0.75% more. Elsewhere containers' nubOrd strings_noFusion_distinct takes 1.9% more, intset map:asc, and mapMonotonic at -O1, about 1.0% to 1.4% more, intmap fromList:asc:fusion 0.99% more, and at -O1 intset fromAscList and fromAscList:sparse 2.6% and 0.96% more and set alterF:insert:present 0.54% more; nofib's smallpt takes 0.53% more, digits-of-e2 0.28% more at -O2 and -O1 and fannkuch-redux 0.27% more at -O2. And where the block now allocated first fixes a join's registers for the blocks after it: megaparsec's count', some, skipSome and sepEndBy1 take more moves an element and reachOffsetNoLine at -O1 more an iteration, a continuation's reloads landing in other registers; containers' fromAscListWithKey and fromDescListWithKey, union-common, index, symmetricDifference, alterF, graphFromEdges and stronglyConnCompR take a move or a shuffle more at a join; nofib's boyer2 takes 0.22% more at -O2, getLUT's loop head given the list in %rsi where both back edges return the tail in %rbx, and reverse-complement 0.23% more at -O2, its object taking 2.1% more bytes, Main_main2 spilling more to the C stack under the new order; and in orthotope's A2T benchmark == and /= over large boxed arrays take up to 4.2% more, each element loaded into %rax and then moved into %rbx, where its window and stride over large boxed arrays gain by the same shape the other way. Narrower toggles each revert one row at a cost. Making a cyclic SCC that holds an entry not pushed at the start wait for a jump to reach it reverts graph buildG's 0.93%, but makes intmap lookup_mixed take 5.1% more. Letting an entry wait only while its target, not yet reached, has another predecessor not yet allocated that runs over 1.2 times as often as the entry reverts nofib's puzzle, 0.58% more at -O2 and 1.2% at -O1, but gives back containers' tree fold1 gains. Setting no entry aside reverts megaparsec's choice, 1.2% more at -O1, but makes megaparsec's benchmarks take 3.0% and 1.3% more. Ranking every entry above the other SCCs, rather than by its hottest jump target, reverts map alterF's lookup present, 0.79% and 0.39% more at -O2 and -O1, but gives back the gains of intset mapMonotonic at -O2 and of the spanAntitone rows, and adds to scs's rise. Against its parent, rows also rising past their bars: nofib's fasta 2.6% at -O2, puzzle 0.58% at -O2 and 1.2% at -O1, mandel2 0.29% at -O2 and cacheprof 0.21% at -O1; containers' map fromListWith-asc:fusion and fromListWithKey-asc:fusion 0.97% and fromDistinctDescList:fusion 0.91% at -O2, buildG's other rows 0.12% to 0.26%, intset fromRange 0.19% at -O2, sequence lookup.10 0.19%, and intset spanAntitone:sparse 0.14% at -O2 and spanAntitone:dense 0.17% at -O1; megaparsec's scientific benchmarks 0.96% to 1.2% at -O2 and up to 0.43% at -O1, and sepBy and sepBy1 0.31% to 0.37% at -O1; vector's next/prevPermutationBijective rows 1.3% to 1.6% at -O2; and the small cells of orthotope's A2T sample, by up to 14 instructions a call, == over small dense Storable arrays the most, and ==.rank1 over them 1.8%, the most in proportion. The estimate and the order are the compile cost: the stage-1 compiler allocates at most 0.028% more at -O0 (T9961) and 0.054% more at -O and -O2 (T12707 at -O) compiling perf/compiler's T3294, T12707, T783 and T9961, and runs up to 0.39% more instructions (T783 at -O); compiling MR 16269's CmmDiamondChain at -O1 and -O2 it runs 0.56% more instructions and allocates 0.061% more. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear allocates 17% more (11.39 against 9.77 GB). Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - c88080d4 by Mikolaj Konarski at 2026-11-13T19:46:58+01:00 Propagate wide move destinations back, preferring the target's register The last preference of "Prefer the register a later block moves a vreg into where it dies", a vreg's wide destination, now reaches back along moves: wideMoveDests also gives a vreg moved where it dies, in a warm block, into a vreg that has a wide destination, that destination, up to four moves back, and the walk of the blocks checks it as it checks the others. A vreg given a destination so first takes the first-used register of the vreg it is moved into, the claims test skipped, as that vreg, dead, still claims its register: given the destination itself, a closure moved into a join's vreg took the register that vreg is moved into later, not the one it has at the join, and every path into the join ended in a move (containers' map fromListWith-asc, 1.26% more at -O1). Where a procedure has no candidate the propagation returns at once, and it shares its list of moves with the walk. In containers' tree PostOrder foldl'_sum a loop's carry is now computed in R2's %r14, where the recursive call takes it, rather than in another register moved there and back. Measured on x86-64 against its parent, in instructions: vector's maximumOn takes 15.4% fewer, containers' tree PostOrder folds 0.76% to 4.4% fewer, nofib's k-nucleotide 0.55% fewer at -O2 and 0.49% at -O1, and clausify and digits-of-e2 0.31% to 0.39% fewer at both. The propagation is a trade, its toggle propagating along no move, which reverts every gain with the rises: against its parent, map fromDescListWithKey takes 0.33% more at -O1, a move every fourth element where the step entered after each descLinkTop or ascLinkTop swaps the stack and its left subtree. Megaparsec's reachOffsetNoLine-0 rows also take 0.63% more at -O1 against the parent. A propagated destination yields to a vreg directly destined for that register and born while the propagated one is live only where the estimate of "Add an estimate of block frequencies for the linear allocator" runs that vreg's own move into the register more often than the move ending the propagated chain, the walk of the blocks then also taking the blocks that write such a vreg: this takes back the rows of map fromAscList and fromDescList at -O2, 0.36% of their 0.39% more, and keeps maximumOn's gain and the fused rows. fromDescListWithKey's -O1 rise stays the trade, the estimate rating its loop exit above its in-loop tail call. The stage-1 compiler allocates at most 0.015% more, compiling perf/compiler's T9961 at -O0. Compiled by the stage-1 compiler, as when building stage 2, GHC.CmmToAsm.Reg.Linear allocates 13% more (12.86 against 11.39 GB). Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 8d751969 by Mikolaj Konarski at 2026-11-13T19:46:59+01:00 Give a vreg the register a recorded join holds it in Where a register is free for a vreg but a recorded jump target's assignment has the vreg in another one, held by a vreg that no instruction left in the block reads and that the recorded jump targets have in its slot, allocRegsAndSpill_spill now spills the holder, a store that jump would need anyway and none where the holder is in its slot already, and gives the vreg its register in place of the free one. The test uses the position of each instruction in its block and the block's last reads of the vregs live out of it, built where the test consults them. Measured on x86-64 against its parent, in instructions: megaparsec's manyTill benchmarks take 0.12% to 0.16% fewer at -O2, and nofib's puzzle 0.23% fewer at -O2 and 1.2% fewer at -O1, no benchmark taking more. The stage-1 compiler allocates 0.084% to 0.14% more compiling at -O0. Assisted-by: Claude Opus 5.5 - - - - - cc1cfbde by Mikolaj Konarski at 2026-11-13T19:46:59+01:00 Spill a vreg its block reads no more Of the vregs in both a register and their slot, else of those in a register only, allocRegsAndSpill_spill evicts the first that no instruction left in the block reads, else the first, except that a vreg live into a jump target with no recorded assignment that another block jumps to as well counts as read again where neither the block nor that target is in a cycle. Evicted, such a vreg would be in its slot in the assignment the block records for the join, so that every later jump there would store it and the code after the join reload it: in megaparsec's someTill the cold paths of a UTF-8 decoder, allocated before the hot one, so cost a store and a reload an element. Where the block or that target is in a loop, as a loop's head is, the eviction stands: there it keeps a register free for the loop. The victim is sought in one fold over the assignment, and only where a vreg of the evicted register class is live out of the block, the previous choice standing elsewhere; the map of last reads is built only where it is consulted, and a procedure's joins outside cycles once, where building a block's last reads first consults them. Before that choice, the previous commit's rule applies where no register is free as well: where a recorded jump target's assignment has the vreg in a register whose holder no instruction left in the block reads, and one such assignment has the holder in its slot and none in a register, the holder goes to its slot here rather than on the way to that target, and the vreg takes its register. The test runs only where a vreg of the class is live out of the block, as such a holder is, and where an assignment it could consult is recorded. With it at the end of an earlier form of the series, against that end, nofib's puzzle at -O2, containers' bcc.star and megaparsec's scientific benchmarks take fewer instructions, no benchmark of nofib, containers or megaparsec taking more beyond its noise, and the compiler's allocation and instructions barely rise in each compilation measured. Each of allocRegsAndSpill_spill's evictions now ends in one local function, evicted, which updates the assignment, loads the vreg if need be and allocates the rest: the previous commit's rule ends in it, and so do master's two cases of eviction in place of their own copies of that code, the case of a vreg in both a register and its slot setting the assignment before the load rather than after, as the rule does, neither reading what the other writes, and the case of one in a register only keeping its spillR and recordSpill. Measured on x86-64 against its parent, in instructions, besides the rows above: vector's awshcc takes 4.7% fewer at -O2, tridiag 1.7% and quickhull 1.0%, containers' IntSet and IntMap union and symmetricDifference benchmarks fall at -O2, and nofib's dom-lt takes 0.73% fewer at -O2 and 0.72% at -O1 and scs 0.45% at both, no benchmark of those suites taking more beyond its noise. With the previous commit the stage-1 compiler allocates 0.14% more compiling perf/compiler's T3294 at -O0, and compiling MR 16269's CmmDiamondChain it runs 0.45% to 0.54% more instructions and allocates 0.40% to 0.49% more, part of them this commit's set of a procedure's joins outside cycles. In orthotope's A2T benchmark, against the previous commit, the rule is a trade: ==, /=, compare and < over large Storable arrays take 6.1% to 7.1% more instructions, in a nest whose block before the inner loop, needing a register for the loop's index, evicts the loop's bound, which it reads no more, so that the loop reloads the bound at every trip; max over large strided Unboxed arrays takes 13% fewer, and < over large scaled and zipWith3A over large scalar Unboxed arrays gain alike. Leaving the rule out reverts both. Counting such a vreg as read again where a hotter block reads it, and storing it before a jump into a hotter block or a loop that does not read it, with or without a test of the loop's register pressure, each took back the rise but lost elsewhere. Figures that the per-commit measurements do not cover were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 2d6dd3c4 by Mikolaj Konarski at 2026-11-13T19:46:59+01:00 Copy small loop heads over the jumps to them before block layout Block layout lets one edge into a loop head fall through and makes the others jump: the loop's entry once a run, every other back edge once an iteration. copyLoopHeads, a new NcgImpl method that x86-64 implements in GHC.CmmToAsm.X86.CodeGen and that cmmNativeGen runs between optimizeCFG and sequenceTop where the chain layout follows, copies a loop head of at most eight instructions and a conditional branch over the jumps to it, after register allocation: a block whose one successor is the head, and which ends in a jump to it, ends in the head's instructions instead and goes straight on to the head's successors, whose edges it takes in the CFG, their weights shared out in proportion to the weight of the jump it replaces. A copy into the loop's entry saves the jump into the loop; a copy into a back edge's source rotates the loop for that edge. Note [Copying loop heads]; Note [CFG based code layout] lists the new step. A loop head is a target of a back edge that optimizeCFG now returns with the weights: one of static prediction's loops (mkGlobalWeightsWith returns loopInfo's back edges too), or, where static prediction does not run, one of findBackEdges', which optHsPatterns raises. copyLoopHeads looks only at the jumps to the back edges' targets, and cmmNativeGen runs it only in a procedure with back edges. Where static prediction runs, optimizeCFG also returns those of findBackEdges' back edges that are none of the loops' and not into the entry, which only an irreducible region has and calcFreqs finds, so that the rule below ranks the jumps by layout's back edges. The jump that layout would let fall through takes no copy: of the jumps to the head, the one ranked first by the weights sequenceChain ranks edges by, a back edge raised as preferBackEdges raises it, where it outranks every other edge in but a self loop, which layout never lets fall through; this rule and preferBackEdges share GHC.CmmToAsm.CFG's new layoutEntryNext and raisedBackWeight. That jump's CFG weight becomes the raised one, since the copies can take away the entry edges preferBackEdges raises it above, and the head's out-edges keep their weights, so that the head keeps the loop's body after it where static prediction rates the loop's back edge below its entry. A block that follows a failed heap or stack check takes no copy. Under -g a head's leading unwind annotations are passed over, and left out of its copies, and a head is copied only into a block whose last unwind annotation equals the head's leading one. Measured against the parent commit, in instructions, with no benchmark of the battery rising by more than its noise but megaparsec's skipMany and many at -O1, 1.0% to 1.1% and 0.27% to 0.79% more: at -O2 nofib's programs take 0.21% fewer (fannkuch-redux 2.1%, knights 1.3%, eff/CSD 1.0%, digits-of-e1 1.0%), containers' benchmarks 0.43% fewer (intmap lookup_half 6.9%, lookup_most 5.2%, lookup_hits 5.1%, intset member 3.4%, nubInt issue1202_repeat 3.3%), megaparsec's 0.32% fewer (string' 1.2%, skipManyTill 1.1%) and vector's 1.21% fewer (nextPermutation 5.3%, nextPermutationBijective 3.7% to 4.3%, hybcc 0.97%); at -O1 nofib's 0.19% fewer (fannkuch-redux 1.9%), containers' 0.52%, megaparsec's 0.31% (reachOffsetNoLine 1.6%, reachOffset 0.91% to 1.3%) and vector's 0.94% (leaffix 0.62%, awshcc 0.60%); at -O0, where it does not run, nofib's 0.13% fewer, through the libraries' code. This takes back the trades of the commit that lets a loop's back edge outrank its entry: IntSet's difference and intersection benchmarks take 0.85% to 0.87% fewer instructions than at the parent at -O2 and -O1, nubInt's noFusion_repeat 2.4% fewer, megaparsec's reachOffset at -O1 0.91% to 1.3% fewer; and vector's awshcc at -O1, whose loop's two back edges both jumped, executes fewer jumps a call, those of one of those back edges among them. Code grows: nofib's objects' text by 0.70% at -O2 and 0.57% at -O1, the stage-2 compiler's by 0.75%. The stage-1 compiler allocates 0.018% more compiling perf/compiler's T9961 at -O, 0.043% more for T12707 and 0.009% more for T783, and the stage-2 compiler 0.11% and 0.13% more for nofib's puzzle and reptile at -O2, its code generator working on the copies; with no copying at -O0, the stage-1 compiler allocates up to 0.042% more, for passing the back edges on. Each rule that picks the jump kept took back rises of a version without it, measured from scratch or with the stage-1 compiler: copying every jump made the loop of two blocks in nofib's spectral-norm a block branching to itself, 2.9% more; keeping the heaviest jump by raw weight copied the one layout let fall through, in intmap's foldMap_elem (2.3% more), intset's fromAscList (3.4%) and base's eqString (nofib's expert 0.26%); letting the head's out-edges lose the copies' weights gave intset's fromAscList's body to the copy of its entry, and leaving the kept jump's weight as it was cost nofib's mkhprog 0.55%. The bound of eight instructions: at four, nubInt's issue1202_repeat keeps a third of its gain; at six, nofib's x2n1 runs 0.86% more instructions at -O2 and at -O1, in the loops of (^), whose heads hold eight. Against six, eight trades code size for run time: no program runs more instructions or allocates more by 0.2%, and nofib's objects grow by 0.01% in total at -O2 and 0.03% at -O1, x2n1's by 3.1%. A bound of ten gained no more, its objects larger; nor did heads of up to 64 copied only over a jump weighted at least a sixteenth for each instruction beyond six, their objects larger too. Not taken: a block ending in a conditional branch and a jump to the head copying it too, which moved nothing in nofib; and a second pass, its back edges found again by findBackEdges, which cost CmmDiamondChain 0.5% more compile allocation and gained no more than the rules above. Figures of variants not taken, and others that the per-commit measurements do not cover, were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - ffac8b01 by Mikolaj Konarski at 2026-11-13T19:46:59+01:00 Use one estimator of block frequencies for the layout and the allocator Static prediction made the layout's estimate by mkGlobalWeights over LabelMaps: loopInfo's dominators and loops, staticBranchPrediction's probabilities, normalised by cfgEdgeProbabilities, and calcFreqs' fixpoint; blockFrequencies made the linear allocator's in two arrays by the same rules. Both are now made by one estimator, freqEstimate, the allocator's array code, which returns the probabilities and the back edges too, on two CFGs: staticPredCfg calls it on the CFG shortcutting leaves, and blockFrequencies on the CFG as instruction selection gives it; the graph allocator's spill costs take blockFrequencies, and loopInfo, LoopInfo, mkGlobalWeights, mkGlobalWeightsWith, staticBranchPrediction, cfgEdgeProbabilities, calcFreqs and CFG's revPostorderFrom are deleted, with the commented-out traces naming them. Where a loop head has back edges from blocks it dominates and from blocks it does not, its loop is now the dominated ones', as loopInfo's was, where blockFrequencies left the head out; and a loop's levels count the blocks reached from its warm back edges, as staticBranchPrediction counted them, where blockFrequencies counted the whole loop. calcFreqs' irreducible skip stays for the layout: given True, as staticPredCfg gives it, freqEstimate skips a block entered by a back edge from a block it does not dominate, which then runs once each time a loop holding it, or the procedure, runs where it heads a loop, and else never; given False, as blockFrequencies gives it, it sums the block's inflow as before. Measured against its parent. Compiling, the stage-1 compiler runs 7.49% and 7.47% fewer instructions and allocates 8.3% less on MR 16269's CmmDiamondChain at -O1 and -O2, 2.8% and 2.6% fewer instructions on T783 at -O and -O2, 2.5% and 2.3% on T12707, 0.68% and 0.67% on T3294 and 0.060% and 0.068% on T9961, and moves by 0.014% or less at -O0; the stage-2 compiler runs 2.3% and 3.4% fewer instructions on nofib's puzzle at -O1 and -O2 and, over nofib's modules, 1.3% and 1.4% fewer instructions and 2.0% and 2.1% less allocation at -O1 and -O2 (geometric means). The generated code is the same at -O0; at -O1 and -O2, a few of nofib's objects differ, the estimates differing by rounding only but for the allocator's of one procedure in spectral/para at -O2, which moves by the rule above; no nofib program moves by 0.2% in instructions or allocation, and at -O1 and -O2 containers' benchmarks move by 0.046% at most, megaparsec's by none past 0.05%, and vector's by 0.014% at most. Over containers at -O1 and -O2 and nofib at -O1 and -O2, no two-way branch's probability moves and the back edges are the same as the old estimator's, and the layout's frequencies differ from its by rounding only. Assisted-by: Claude Opus 5.5 - - - - - 2bc9f727 by Mikolaj Konarski at 2026-11-13T19:46:59+01:00 Count irreducible regions' blocks in the layout's frequencies The layout's estimate skipped, as calcFreqs did, every block entered by a back edge from a block it does not dominate: such a block ran once each time a loop holding it, or the procedure, ran where it headed a loop, and else never, whatever flowed into it. freqEstimate now sums its inflow as for any other block, as the allocator's estimate does, and loses its Bool argument. Measured against its parent. Compiling, the stage-1 compiler runs 0.007% fewer instructions on MR 16269's CmmDiamondChain at -O1 and -O2, and within 0.007% elsewhere. At -O1 and -O2, about a quarter of nofib's objects differ. nofib's mkhprog runs 0.53% more instructions at -O2: in writeln's loop, static prediction takes the branch to the loop's head for 7:1 likely where the other side runs 18678 times to its 54, and the skip left the continuation on that side with more frequency than flowed into it, which by accident ranked its jump to the head first; now copying the head into that jump leaves one jump an iteration. eliza runs 0.20% fewer instructions at -O1, the branches falling by as many, and megaparsec's many and skipMany at -O1 0.72% to 1.06% fewer, one branch instruction an element; containers' benchmarks move by 0.063% at most, vector's by none past 0.05% but the (next|prev)Permutation baseline row's 0.10% fall, a row jumping by as much either way elsewhere in the series. Over containers at -O1 and -O2 and nofib at -O1 and -O2, no two-way branch's probability moves and the back edges stay the same; the frequencies differ by more than 1% from the parent's in one or two procedures in a hundred of containers' and of nofib's at -O1 and -O2. Assisted-by: Claude Opus 5.5 - - - - - b01d1640 by Mikolaj Konarski at 2026-11-13T19:46:59+01:00 Walk liveness first over the instructions as the code generator gives natCmmTopToLive wrapped every instruction as LiveInstr (Instr i) Nothing, in a list of its own, which the first liveness walk dropped at once for a LiveInstr carrying the liveness. Now natCmmTopToLive returns the procedure's SCCs of NatBasicBlocks, and the walk takes an accessor giving each element's InstrSR: Instr on the first walk, a LiveInstr's own when the graph allocator walks again. regLivenessOf is INLINE and livenessSCCs is a wrapper around a local loop, so that the first walk's copy for x86 has the accessor constant in its loops over the SCCs: as a plain recursive function, specialised to x86 with the accessor an argument, it made the compiler run 0.046% more instructions and allocate 0.056% more compiling CmmDiamondChain at -O0. livenessBlock takes the accessor as an argument: INLINE, it made the compiler run 0.05% more instructions compiling T3294 at -O0. livenessBack is a wrapper around a local loop too, which does not pass the accessor, the platform and the block map again at each instruction. sccBlocks, master's, now returns beside the SCCs a map of each block's jump targets, the lists its graph's nodes carry, and LiveInfo, master's, carries the map in a fifth field, matched with one field more at each of its sites: Liveness.hs's, Linear.regAlloc's, and the graph allocator's in Spill.hs, SpillClean.hs and SpillCost.hs, which pass it through or ignore it. livenessCyclic takes a block's predecessors in the SCC from the map and linearRegAlloc' its context's rc_succs, where each walked every instruction of the SCC or of the procedure (jumpSuccs, deleted): the compiler runs fewer instructions compiling T9961 at -O0 and allocates less compiling CmmDiamondChain at -O0. Measured with stage-1 compilers against the parent commit on x86-64: the assembly of perf/compiler's T3294, T12707, T783 and T9961 at -O0, -O and -O2 and of MR 16269's CmmDiamondChain at -O0, -O1 and -O2 is byte-identical, and so is that of T3294 and T9961 at -O under -fregs-graph and -fregs-iterative. The stage-1 compiler allocates 1.39% less compiling T3294 at -O0, 1.25% less for T9961, 0.96% for T12707 and 0.85% for T783, 0.041% to 0.47% less at -O and -O2, and 0.51% to 0.58% less for CmmDiamondChain, and runs 0.039% to 0.85% fewer instructions, counted with an allocation area larger than all a compilation allocates. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - d52205be by Mikolaj Konarski at 2026-11-13T19:46:59+01:00 Document behaviour of the NCG's CFG, layout and register allocators To move into a merge request of its own. Comments and documentation only, on behaviour the earlier commits do not change; the generated code is the same. Dead code elimination is off under -finfo-table-map (ISSUE 20428), so the liveness pass gets no CFG and none is kept after register allocation: there is no static prediction for the layout and no chain layout under -fblock-layout-cfg. In GHC.CmmToAsm.Reg.Graph.SpillCost, a comment says that the block frequencies scale only the counts of uses and definitions, on which no spill choice depends. In GHC.CmmToAsm.CFG, Note [CFG Edge Weights] gave the default weight as 20k, where defaultWeights has 1000, and said that the false side of a regular branch is preferred, where both sides get the same weight and optHsPatterns' favourFewerPreds may prefer one by its predecessors, and that calls are ignored completely, where the layout leaves a call's edge out only while it builds chains and divides its weight by 64 when it merges them; it now also says that under -fcmm-static-pred the weights become estimated frequencies, for the layout and, estimated before allocation, for the linear allocator. Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout also said that calls are ignored, and now says how the layout treats them. Comments now say that edges of equal weight fall back on label order, which means nothing, and that where shortcutting redirects an edge onto one already there, one of them keeps its EdgeInfo and their weights are not summed; in GHC.CmmToAsm.BlockLayout, that allEdges' relevantWeight differs from directEdges'. Note [CFG based code layout] now says that the layout's loop analysis and staticPredCfg run for the layout only under -fcmm-static-pred, and the users' guide that -fcmm-static-pred works only on x86-64, for the linear allocator's order and, after register allocation and without -finfo-table-map, for the layout. In X86's genCondBranch', a comment says that the 3 added to the weight of a floating-point comparison's false edge breaks layout ties toward the side GHC.Cmm.ContFlowOpt makes likely. In the linear allocator, Note [Unique order in the linear allocator] says which decisions take the order of the vregs' uniques as a ranking, the spill victim and the order in which saveClobberedTemps moves values out of clobbered registers, and that it orders joinToTargets' fixup moves. The comments that said deterministic code generation was not supported, which -fobject-determinism provides, now say, there and in the liveness pass and the graph allocator, whether the order matters, and in GHC.Cmm.Node, GHC.Cmm.Reg and GHC.Platform.Reg that it is deterministic only where the uniques are. In GHC.CmmToAsm.Reg.Liveness, the comment on the SCCs' order says that no block may fall through before allocation, and liveDieRead's haddock that at a branch it also holds the registers live into its targets only. Comments that were wrong before the series are corrected too. Step (j) of the linear allocator's outline, re-adding a dead spilled register's stack slot to the free list, is marked as not done, a StackMap never freeing a slot. On AArch64, getFreeRegs scans the integer registers from x18 down, not from 28. On i386, the comment at classOfRealReg in GHC.CmmToAsm.X86.Regs numbers the registers with 8-bit versions 0-3 and the allocatable ones 0, 2 and 3, where it said 1-4 and 1, 3 and 4. FreeRegs' executable specification gives noFreeRegs as [] and getFreeRegs each instance's fixed order, where it handed out the registers most recently released first. X86's stmtToInstrs no longer assumes the condition likely false: GHC.Cmm.ContFlowOpt also inverts a condition whatever its likelihood where the false target has more than one predecessor. GHC.CmmToAsm.Reg.Linear.State cites Note [The one-shot state monad trick] on one line, where the notes linter matches it. linearRegAlloc's haddock and the comment over process say that a block is allocated before a jump into it if it is any of the procedure's entry blocks, not only its first, and that process drops a block whose assignment never gets set, where the comment said that it would loop. Note [CFG Edge Weights] gives likely and unlikely branches the 75% and 25% the default weights give them, where it said more than 80% and less than 20%. Assisted-by: Claude Opus 5.5 - - - - - 112 changed files: - compiler/GHC/Cmm.hs - compiler/GHC/Cmm/ContFlowOpt.hs - compiler/GHC/Cmm/Graph.hs - compiler/GHC/Cmm/Info/Build.hs - compiler/GHC/Cmm/LayoutStack.hs - compiler/GHC/Cmm/Lint.hs - compiler/GHC/Cmm/Liveness.hs - compiler/GHC/Cmm/Node.hs - compiler/GHC/Cmm/Opt.hs - compiler/GHC/Cmm/Pipeline.hs - compiler/GHC/Cmm/ProcPoint.hs - compiler/GHC/Cmm/Reg.hs - compiler/GHC/Cmm/Sink.hs - compiler/GHC/Cmm/UniqueRenamer.hs - compiler/GHC/Cmm/Utils.hs - compiler/GHC/CmmToAsm.hs - compiler/GHC/CmmToAsm/AArch64.hs - compiler/GHC/CmmToAsm/AArch64/CodeGen.hs - compiler/GHC/CmmToAsm/BlockLayout.hs - compiler/GHC/CmmToAsm/CFG.hs - compiler/GHC/CmmToAsm/Instr.hs - compiler/GHC/CmmToAsm/LA64.hs - compiler/GHC/CmmToAsm/Monad.hs - compiler/GHC/CmmToAsm/PPC.hs - compiler/GHC/CmmToAsm/RV64.hs - compiler/GHC/CmmToAsm/Reg/Graph.hs - compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs - compiler/GHC/CmmToAsm/Reg/Graph/SpillClean.hs - compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs - compiler/GHC/CmmToAsm/Reg/Linear.hs - compiler/GHC/CmmToAsm/Reg/Linear/AArch64.hs - compiler/GHC/CmmToAsm/Reg/Linear/Base.hs - compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs - compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs - compiler/GHC/CmmToAsm/Reg/Linear/State.hs - compiler/GHC/CmmToAsm/Reg/Liveness.hs - compiler/GHC/CmmToAsm/Reg/Regs.hs - compiler/GHC/CmmToAsm/X86.hs - compiler/GHC/CmmToAsm/X86/CodeGen.hs - compiler/GHC/CmmToAsm/X86/Instr.hs - compiler/GHC/CmmToAsm/X86/Regs.hs - compiler/GHC/Data/Graph/Directed.hs - compiler/GHC/Driver/Config/CmmToAsm.hs - compiler/GHC/Driver/Config/StgToCmm.hs - compiler/GHC/Platform/Reg.hs - compiler/GHC/StgToCmm/Bind.hs - compiler/GHC/StgToCmm/Config.hs - compiler/GHC/StgToCmm/DataCon.hs - compiler/GHC/StgToCmm/Monad.hs - compiler/GHC/StgToCmm/Utils.hs - docs/users_guide/using-optimisation.rst - rts/Weak.c - rts/include/Cmm.h - + testsuite/tests/cmm/should_compile/T27800.cmm - + testsuite/tests/cmm/should_compile/T27980.cmm - + testsuite/tests/cmm/should_compile/T8327.cmm - testsuite/tests/cmm/should_compile/all.T - + testsuite/tests/cmm/should_compile/cmm_fold_elemAt.hs - + testsuite/tests/cmm/should_compile/cmm_fold_lit.cmm - + testsuite/tests/cmm/should_compile/cmm_fold_scaled.cmm - + testsuite/tests/cmm/should_compile/cmm_fold_scaled.stderr - testsuite/tests/cmm/should_run/all.T - + testsuite/tests/cmm/should_run/cmm_addnf.hs - + testsuite/tests/cmm/should_run/cmm_addnf.stdout - + testsuite/tests/cmm/should_run/cmm_addnf_cmm.cmm - + testsuite/tests/cmm/should_run/cmm_regoff.hs - + testsuite/tests/cmm/should_run/cmm_regoff.stdout - + testsuite/tests/cmm/should_run/cmm_regoff_cmm.cmm - + testsuite/tests/cmm/should_run/cmm_scaledlit.hs - + testsuite/tests/cmm/should_run/cmm_scaledlit.stdout - + testsuite/tests/cmm/should_run/cmm_scaledlit_cmm.cmm - + testsuite/tests/cmm/should_run/cmm_sinkoff.hs - + testsuite/tests/cmm/should_run/cmm_sinkoff.stdout - + testsuite/tests/cmm/should_run/cmm_sinkoff_cmm.cmm - + testsuite/tests/cmm/should_run/cmm_swoff.hs - + testsuite/tests/cmm/should_run/cmm_swoff.stdout - + testsuite/tests/cmm/should_run/cmm_swoff_cmm.cmm - + testsuite/tests/codeGen/should_compile/ClosureTblAmode.hs - + testsuite/tests/codeGen/should_compile/ClosureTblAmode.stderr - + testsuite/tests/codeGen/should_compile/EnumTagOffset.hs - + testsuite/tests/codeGen/should_compile/EnumTagOffset.stderr - + testsuite/tests/codeGen/should_compile/StackLayoutCallLoop.hs - + testsuite/tests/codeGen/should_compile/StackLayoutTagLoop.hs - + testsuite/tests/codeGen/should_compile/T20333.hs - + testsuite/tests/codeGen/should_compile/T20333.stderr - + testsuite/tests/codeGen/should_compile/T20333b.hs - + testsuite/tests/codeGen/should_compile/T20333b.stderr - + testsuite/tests/codeGen/should_compile/T20333c.hs - + testsuite/tests/codeGen/should_compile/T20333c.stderr - + testsuite/tests/codeGen/should_compile/T20334.hs - + testsuite/tests/codeGen/should_compile/T20334.stderr - + testsuite/tests/codeGen/should_compile/T27991.hs - testsuite/tests/codeGen/should_compile/all.T - testsuite/tests/codeGen/should_gen_asm/T24813.asm - testsuite/tests/codeGen/should_gen_asm/bytearray-memcpy-unroll.asm - testsuite/tests/codeGen/should_gen_asm/bytearray-memset-unroll.asm - + testsuite/tests/regalloc/T27619.hs - + testsuite/tests/regalloc/T27981.hs - testsuite/tests/regalloc/all.T - testsuite/tests/regalloc/regalloc_unit_tests.hs - + testsuite/tests/simd/should_run/T27638.hs - + testsuite/tests/simd/should_run/T27638.stdout - + testsuite/tests/simd/should_run/T27638a.hs - + testsuite/tests/simd/should_run/T27638a.stdout - + testsuite/tests/simd/should_run/T27638b.hs - + testsuite/tests/simd/should_run/T27638b.stdout - + testsuite/tests/simd/should_run/T27638c.hs - + testsuite/tests/simd/should_run/T27638c.stdout - + testsuite/tests/simd/should_run/T27638d.hs - + testsuite/tests/simd/should_run/T27638d.stdout - + testsuite/tests/simd/should_run/T27638e.hs - testsuite/tests/simd/should_run/all.T The diff was not included because it is too large. View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/02495b9a473a42b93e939a0e216514f... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/02495b9a473a42b93e939a0e216514f... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Mikolaj Konarski (@Mikolaj)