[Git][ghc/ghc][wip/sjakobi/T27448] 2 commits: NCG: Rewrite loopInfo.mkDomMap
Simon Jakobi pushed to branch wip/sjakobi/T27448 at Glasgow Haskell Compiler / GHC Commits: 95b528fd by Simon Jakobi at 2026-11-20T03:05:35+01:00 NCG: Rewrite loopInfo.mkDomMap mkDomMap used to build an intermediate association list with (++) and a recursive concatMap before handing it to mapFromList, performing work proportional to the number of blocks times the depth of the dominator tree. The new code builds the LabelMap directly, with one mapInsert per dominator-tree node. This reduces allocations when compiling the new CmmDiamondChain test by roughly 27% at -O1 and -O2. The map now holds each block's dominators, including the block itself and the procedure entry. This changes which edges loopInfo reports as back edges in two ways: - Previously, a self-loop was reported as a back edge only if its block was a leaf of the dominator tree (#28093). - Loops headed by the entry block are now detected too (#28083). Closes #27448, #28083 and #28093. Metric Decrease: T26425 Assisted-by: Claude Fable 5.1 - - - - - 339a921d by Simon Jakobi at 2026-11-20T03:24:34+01:00 NCG: Add types and documentation to calcFreqs Assisted-by: Claude Fable 5.2 - - - - - 10 changed files: - compiler/GHC/CmmToAsm/CFG.hs - + testsuite/tests/cmm/should_compile/T28083.cmm - + testsuite/tests/cmm/should_compile/T28083.stderr - + testsuite/tests/cmm/should_compile/T28093.cmm - + testsuite/tests/cmm/should_compile/T28093.stderr - + testsuite/tests/cmm/should_compile/T28093_cas.cmm - + testsuite/tests/cmm/should_compile/T28093_cas.stderr - testsuite/tests/cmm/should_compile/all.T - testsuite/tests/perf/compiler/all.T - + testsuite/tests/perf/compiler/genCmmDiamondChain Changes: ===================================== compiler/GHC/CmmToAsm/CFG.hs ===================================== @@ -797,7 +797,7 @@ loopLevels cfg root = liLevels loopInfos loopInfos = loopInfo cfg root data LoopInfo = LoopInfo - { liBackEdges :: [(Edge)] -- ^ List of back edges + { liBackEdges :: [(Edge)] -- ^ The edges whose target dominates their source , liLevels :: LabelMap Int -- ^ BlockId -> LoopLevel mapping , liLoops :: [(Edge, LabelSet)] -- ^ (backEdge, loopBody), body includes header } @@ -840,15 +840,19 @@ loopInfo cfg root = LoopInfo { liBackEdges = backEdges rooted = coerce (root, graph) tree = coerce (Dom.domTree rooted) :: Tree BlockId - -- Map from Nodes to their dominators + -- The dominators of each block, including the block itself. domMap :: LabelMap LabelSet - domMap = mkDomMap tree + domMap = go setEmpty mapEmpty tree + where + go :: LabelSet -> LabelMap LabelSet -> Tree BlockId -> LabelMap LabelSet + go doms acc (Node lbl children) + = let !doms' = setInsert lbl doms + in foldl' (go doms') (mapInsert lbl doms' acc) children edges = edgeList cfg :: [(BlockId, BlockId)] -- We can't recompute nodes from edges, there might be blocks not connected via edges. nodes = getCfgNodes cfg :: [BlockId] - -- identify back edges isBackEdge (from,to) | Just doms <- mapLookup from domMap , setMember to doms @@ -884,19 +888,6 @@ loopInfo cfg root = LoopInfo { liBackEdges = backEdges loopCount n = length $ nub . map fst . filter (setMember n . snd) $ bodies in map (\n -> (n, loopCount n)) $ nodes :: [(BlockId, Int)] - mkDomMap :: Tree BlockId -> LabelMap LabelSet - mkDomMap root = mapFromList $ go setEmpty root - where - go :: LabelSet -> Tree BlockId -> [(Label,LabelSet)] - go parents (Node lbl []) - = [(lbl, parents)] - go parents (Node _ leaves) - = let nodes = map rootLabel leaves - entries = map (\x -> (x,parents)) nodes - in entries ++ concatMap - (\n -> go (setInsert (rootLabel n) parents) n) - leaves - -- We make the CFG a Hoopl Graph, so we can reuse revPostOrder. newtype BlockNode (e :: Extensibility) (x :: Extensibility) = BN (BlockId,[BlockId]) @@ -918,6 +909,13 @@ revPostorderFrom cfg root = toNode bid = BN (bid,getSuccessors cfg $ bid) +-- | A block's index in the reverse post order of its procedure, starting at +-- 0 for the entry. +type Vertex = Int + +type VertexMap = IntMap + +type VertexSet = IntSet -- | We take in a CFG which has on its edges weights which are -- relative only to other edges originating from the same node. @@ -952,7 +950,7 @@ mkGlobalWeights root localCfg blockFreqs' = mapFromList $ map (first fromVertex) (assocs blockFreqs) :: LabelMap Double edgeFreqs' = fmap fromVertexMap $ fromVertexMap edgeFreqs - fromVertexMap :: IM.IntMap x -> LabelMap x + fromVertexMap :: VertexMap x -> LabelMap x fromVertexMap m = mapFromList . map (first fromVertex) $ IM.toList m revOrder = revPostorderFrom localCfg root :: [BlockId] @@ -972,13 +970,13 @@ mkGlobalWeights root localCfg calcBody (backedge, blocks) = (toVertex $ snd backedge, sort . map toVertex $ (setElems blocks)) - vertexMapping = mapFromList $ zip revOrder [0..] :: LabelMap Int - blockMapping = listArray (0,mapSize vertexMapping - 1) revOrder :: Array Int BlockId + vertexMapping = mapFromList $ zip revOrder [0..] :: LabelMap Vertex + blockMapping = listArray (0,mapSize vertexMapping - 1) revOrder :: Array Vertex BlockId -- Map from blockId to indices starting at zero - toVertex :: BlockId -> Int + toVertex :: BlockId -> Vertex toVertex blockId = expectJust $ mapLookup blockId vertexMapping -- Map from indices starting at zero to blockIds - fromVertex :: Int -> BlockId + fromVertex :: Vertex -> BlockId fromVertex vertex = blockMapping ! vertex {- Note [Static Branch Prediction] @@ -1162,13 +1160,13 @@ staticBranchPrediction _root (LoopInfo l_backEdges loopLevels l_loops) cfg = -- We normalize all edge weights as probabilities between 0 and 1. -- Ignoring rounding errors all outgoing edges sum up to 1. -cfgEdgeProbabilities :: CFG -> (BlockId -> Int) -> IM.IntMap (IM.IntMap Prob) +cfgEdgeProbabilities :: CFG -> (BlockId -> Vertex) -> VertexMap (VertexMap Prob) cfgEdgeProbabilities cfg toVertex = mapFoldlWithKey foldEdges IM.empty cfg where foldEdges = (\m from toMap -> IM.insert (toVertex from) (normalize toMap) m) - normalize :: (LabelMap EdgeInfo) -> (IM.IntMap Prob) + normalize :: (LabelMap EdgeInfo) -> (VertexMap Prob) normalize weightMap | edgeCount <= 1 = mapFoldlWithKey (\m k _ -> IM.insert (toVertex k) 1.0 m) IM.empty weightMap | otherwise = mapFoldlWithKey (\m k _ -> IM.insert (toVertex k) (normalWeight k) m) IM.empty weightMap @@ -1189,14 +1187,28 @@ cfgEdgeProbabilities cfg toVertex = w/totalWeight | otherwise = panic "impossible" +-- | Compute how often each block runs and each edge is taken per invocation +-- of the procedure, given the probabilities of the edges. +-- -- This is the fixpoint algorithm from -- "Static Branch Prediction and Program Profile Analysis" by Y Wu, JR Larus -- The adaption to Haskell is my own. -calcFreqs :: IM.IntMap (IM.IntMap Prob) -> [(Int,Int)] -> [(Int, [Int])] -> [Int] - -> (Array Int Double, IM.IntMap (IM.IntMap Prob)) +calcFreqs :: VertexMap (VertexMap Prob) + -- ^ Edge probabilities, by source and target. The probabilities of + -- a block's outgoing edges sum to 1. + -> [(Vertex, Vertex)] + -- ^ The back edges, as (source, target) + -> [(Vertex, [Vertex])] + -- ^ For each back edge, its target (the loop header) and the body + -- of its loop. The body includes the header and is in reverse post + -- order. + -> [Vertex] + -- ^ All blocks in reverse post order, so the entry comes first + -> (Array Vertex Double, VertexMap (VertexMap Prob)) + -- ^ Block frequencies, and edge frequencies by source and target calcFreqs graph backEdges loops revPostOrder = runST $ do - visitedNodes <- newArray (0,nodeCount-1) False :: ST s (STUArray s Int Bool) - blockFreqs <- newArray (0,nodeCount-1) 0.0 :: ST s (STUArray s Int Double) + (visitedNodes :: STUArray s Vertex Bool) <- newArray (0,nodeCount-1) False + (blockFreqs :: STUArray s Vertex Double) <- newArray (0,nodeCount-1) 0.0 edgeProbs <- newSTRef graph edgeBackProbs <- newSTRef graph @@ -1207,11 +1219,13 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do let -- See #1600, we need to inline or unboxing makes perf worse. -- {-# INLINE getFreq #-} {-# INLINE visited #-} + visited :: Vertex -> ST s Bool visited b = unsafeRead visitedNodes b + getFreq :: Vertex -> ST s Double getFreq b = unsafeRead blockFreqs b - -- setFreq :: forall s. Int -> Double -> ST s () + setFreq :: Vertex -> Double -> ST s () setFreq b f = unsafeWrite blockFreqs b f - -- setVisited :: forall s. Node -> ST s () + setVisited :: Vertex -> ST s () setVisited b = unsafeWrite visitedNodes b True -- Frequency/probability that edge is taken. getProb' arr b1 b2 = readSTRef arr >>= @@ -1238,10 +1252,10 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do setBackProb b1 b2 = setProb' edgeBackProbs b1 b2 - let -- calcOutFreqs :: Node -> ST s () + let calcOutFreqs :: Vertex -> Vertex -> ST s () calcOutFreqs bhead block = do !f <- getFreq block - forM (successors block) $ \bi -> do + forM_ (successors block) $ \bi -> do let !prob = getProb block bi let !succFreq = f * prob setEdgeFreq block bi succFreq @@ -1249,7 +1263,8 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do when (bi == bhead) $ setBackProb block bi succFreq - let propFreq block head = do + let propFreq :: Vertex -> Vertex -> ST s () + propFreq block head = do -- traceM ("prop:" ++ show (block,head)) -- traceShowM block @@ -1290,13 +1305,17 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do setVisited block calcOutFreqs head block - -- Loops, by nesting, inner to outer + -- One pass per loop. Each pass sets the probabilities of its loop's back + -- edges, which the passes of the enclosing loops then read. + -- FIXME: 'loops' is not ordered inner first. forM_ loops $ \(head, body) -> do forM_ [0 .. nodeCount - 1] (\i -> unsafeWrite visitedNodes i True) -- Mark all nodes as visited. forM_ body (\i -> unsafeWrite visitedNodes i False) -- Mark all blocks reachable from head as not visited forM_ body $ \block -> propFreq block head - -- After dealing with all loops, deal with non-looping parts of the CFG + -- The whole procedure, using the back edge probabilities from the loop passes. + -- FIXME: The entry gets frequency 1 even when an edge leads back to it, + -- which makes every frequency too low by the same factor. forM_ [0 .. nodeCount - 1] (\i -> unsafeWrite visitedNodes i False) -- Everything in revPostOrder is reachable forM_ revPostOrder $ \block -> propFreq block (head revPostOrder) @@ -1310,14 +1329,14 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do return (freqs', graph') where -- How can these lookups fail? Consider the CFG [A -> B] - predecessors :: Int -> IS.IntSet + predecessors :: Vertex -> VertexSet predecessors b = fromMaybe IS.empty $ IM.lookup b revGraph - successors :: Int -> [Int] + successors :: Vertex -> [Vertex] successors b = fromMaybe (lookupError "succ" b graph)$ IM.keys <$> IM.lookup b graph lookupError s b g = pprPanic ("Lookup error " ++ s) $ ( text "node" <+> ppr b $$ text "graph" <+> - vcat (map (\(k,m) -> ppr (k,m :: IM.IntMap Double)) $ IM.toList g) + vcat (map (\(k,m) -> ppr (k,m :: VertexMap Double)) $ IM.toList g) ) nodeCount = IM.foldl' (\count toMap -> IM.foldlWithKey' countTargets (count + 1) toMap) 0 graph @@ -1328,7 +1347,7 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do isBackEdge from to = S.member (from,to) backEdgeSet backEdgeSet = S.fromList backEdges - revGraph :: IntMap IntSet + revGraph :: VertexMap VertexSet revGraph = IM.foldlWithKey' (\m from toMap -> addEdges m from toMap) IM.empty graph where addEdges m0 from toMap = IM.foldlWithKey' (\m k _ -> addEdge m from k) m0 toMap ===================================== testsuite/tests/cmm/should_compile/T28083.cmm ===================================== @@ -0,0 +1,14 @@ +#include "Cmm.h" + +// The entry is a bare goto, so the Cmm control-flow optimiser makes L the +// entry, heading the loop L -> B -> L. Expected: L -> B outweighs the exit +// edge. Without loop detection they tie. +stg_loop { + goto L; +L: + if (R1 > 0) { goto B; } + jump stg_loop [R1]; +B: + R1 = R1 - 1; + goto L; +} ===================================== testsuite/tests/cmm/should_compile/T28083.stderr ===================================== @@ -0,0 +1,7 @@ +==================== CFG Weights - Final ==================== +stg_loop: +digraph { + c1 -> c4[label="0.25000",weight="0.25000"]; + c1 -> c2[label="0.75000",weight="0.75000"]; + c2 -> c1[label="0.75000",weight="0.75000"]; +} ===================================== testsuite/tests/cmm/should_compile/T28093.cmm ===================================== @@ -0,0 +1,14 @@ +#include "Cmm.h" + +// S is a self-loop that dominates the exit block, so it is not a leaf of +// the dominator tree. The entry does work, so it isn't merged into S. +// Expected: the self edge outweighs the exit edge. Without loop detection +// both get weight 0. +stg_self { + R1 = R1 + 1; + goto S; +S: + R1 = R1 - 1; + if (R1 > 0) { goto S; } + jump stg_self [R1]; +} ===================================== testsuite/tests/cmm/should_compile/T28093.stderr ===================================== @@ -0,0 +1,7 @@ +==================== CFG Weights - Final ==================== +stg_self: +digraph { + c1 -> c4[label="1.00000",weight="1.00000"]; + c5 -> c1[label="1.00000",weight="1.00000"]; + c1 -> c1[label="7.00000",weight="7.00000"]; +} ===================================== testsuite/tests/cmm/should_compile/T28093_cas.cmm ===================================== @@ -0,0 +1,17 @@ +#include "Cmm.h" + +// On x86-64 the atomic or is a compare-and-swap loop: a block added by the +// NCG with a self edge of weight 0. That block dominates the loop L -> B -> L. +// Expected: the loop's edges outweigh its exit edge. Without the self edge +// counting as a back edge, every edge after the atomic op gets weight 0. +stg_cas { + W_ old; + (old) = prim %fetch_or64(R2, 1 :: I64); + goto L; +L: + if (R1 > 0) { goto B; } + jump stg_cas [R1, R2]; +B: + R1 = R1 - 1; + goto L; +} ===================================== testsuite/tests/cmm/should_compile/T28093_cas.stderr ===================================== @@ -0,0 +1,11 @@ +==================== CFG Weights - Final ==================== +stg_cas: +digraph { + c4 -> c7[label="1.00000",weight="1.00000"]; + c9 -> n1[label="1.00000",weight="1.00000"]; + n1 -> n2[label="1.00000",weight="1.00000"]; + n2 -> c4[label="1.00000",weight="1.00000"]; + c4 -> c5[label="3.00000",weight="3.00000"]; + c5 -> c4[label="3.00000",weight="3.00000"]; + n1 -> n1[label="7.00000",weight="7.00000"]; +} ===================================== testsuite/tests/cmm/should_compile/all.T ===================================== @@ -2,6 +2,14 @@ setTestOpts( [ req_cmm ]) +def final_cfg_weights(s): + """ + The edge weights of the final CFG, without the block labels, which + depend on uniques. + """ + final = s.split('CFG Weights - Final')[-1] + return '\n'.join(re.findall(r'weight="([^"]*)"', final)) + test('selfloop', [cmm_src], compile, ['-no-hs-main']) test('cmm_sink_sp', [ only_ways(['optasm']), grep_errmsg(r'(\[Sp.*\]).*(=).*(\[.*R1.*\]).*;',[1,2,3]), @@ -11,6 +19,21 @@ test('T16930', normal, makefile_test, ['T16930']) test('T17442', normal, compile, ['']) test('T20725', normal, compile, ['-package ghc']) test('T23610', normal, makefile_test, ['T23610']) +test('T28083', [cmm_src, only_ways(['optasm']), + unless(arch('x86_64'), skip), + when(leading_underscore(), skip), + normalise_errmsg_fun(final_cfg_weights)], + compile, ['-no-hs-main -ddump-cfg-weights']) +test('T28093', [cmm_src, only_ways(['optasm']), + unless(arch('x86_64'), skip), + when(leading_underscore(), skip), + normalise_errmsg_fun(final_cfg_weights)], + compile, ['-no-hs-main -ddump-cfg-weights']) +test('T28093_cas', [cmm_src, only_ways(['optasm']), + unless(arch('x86_64'), skip), + when(leading_underscore(), skip), + normalise_errmsg_fun(final_cfg_weights)], + compile, ['-no-hs-main -ddump-cfg-weights']) test('T24224', [cmm_src, grep_errmsg(r'(F64.*);', [1]), only_ways(['normal'])], compile, ['-no-hs-main -ddump-cmm -dsuppress-all -dsuppress-uniques']) test('T24474', cmm_src, compile, ['-optc-g3']) # Grep for a `... = + .. 42 ..;` occurence from within the dead code block in the cmm dump output. ===================================== testsuite/tests/perf/compiler/all.T ===================================== @@ -38,6 +38,17 @@ test('T3294', compile, ['']) +test('CmmDiamondChain', + [ only_ways(['optasm']), + unless(have_ncg(), skip), + cmm_src, + collect_compiler_stats('bytes allocated', 2), + pre_cmd('./genCmmDiamondChain'), + extra_files(['genCmmDiamondChain']), + ], + compile, + ['-O2 -v0']) + test('T4801', [collect_compiler_runtime(2), only_ways(['normal']), ===================================== testsuite/tests/perf/compiler/genCmmDiamondChain ===================================== @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Generate a Cmm source file that is heavy on control flow. +# +# It produces thousands of basic blocks in a single Cmm graph, +# stressing the control-flow handling of the NCG and Wasm backends. +# +# With the default knobs, the procedure looks like this: +# +# entry +# | +# v +# .---> split0 \ +# | / \ | +# | left0 right0 | stage 0 +# | \ / | +# | join0 / +# | | +# | v +# | split1 ... join15 stages 1 to 15 +# | | +# | v +# '---- latch0 trip0 < 2: back to split0 +# | +# v +# .---> split16 ... join31 chunk 1, same shape +# | | +# '---- latch1 +# | +# v +# ... +# | +# v +# latch127 last chunk returns acc +# +# The variables acc and mix stay live through the whole procedure, and +# every branch condition reads mix, so no stage can be folded away. +# The two arms of a diamond swap their constants, so that common block +# elimination cannot merge them. +# +# Each trip counter is set in the entry block and read only at its own +# latch, so all of them start out live and the procedure spills heavily. +# +# Tuning knobs: +# STAGES Number of diamond stages to generate. Default: 2048 +# LOOP_PERIOD Number of stages per loop chunk. Default: 16 +# OUT Output file. Default: CmmDiamondChain.cmm +# +# Run with STAGES=2 LOOP_PERIOD=2 for a small example of the output. + +: "${STAGES:=2048}" +: "${LOOP_PERIOD:=16}" +: "${OUT:=CmmDiamondChain.cmm}" + +(( STAGES > 0 && LOOP_PERIOD > 0 )) || { + echo "STAGES and LOOP_PERIOD must be positive integers" >&2 + exit 1 +} + +chunk_count=$(( (STAGES + LOOP_PERIOD - 1) / LOOP_PERIOD )) +block_count=$(( 1 + 4 * STAGES + chunk_count )) + +emit() { + printf '%s\n' "$*" +} + +{ + emit "// Generated by genCmmDiamondChain" + emit "//" + emit "// Parameters:" + emit "// STAGES=${STAGES}" + emit "// LOOP_PERIOD=${LOOP_PERIOD}" + emit "//" + emit "// Cmm blocks: ${block_count}" + emit "#include \"Cmm.h\"" + emit + emit "diamond_chain (W_ seed) {" + emit " W_ acc;" + emit " W_ mix;" + for ((chunk = 0; chunk < chunk_count; chunk++)); do + emit " W_ trip${chunk};" + done + emit + emit "entry:" + emit " acc = seed;" + emit " mix = seed + (17 :: W_);" + for ((chunk = 0; chunk < chunk_count; chunk++)); do + emit " trip${chunk} = 0;" + done + emit " goto split0;" + emit + + for ((stage = 0; stage < STAGES; stage++)); do + next_stage=$(( stage + 1 )) + chunk=$(( stage / LOOP_PERIOD )) + k1=$(( 4 * stage + 1 )) + k2=$(( 4 * stage + 2 )) + k3=$(( 4 * stage + 3 )) + k4=$(( 4 * stage + 4 )) + + emit "split${stage}:" + emit " mix = mix + (${k1} :: W_);" + emit " if (((mix + (${k2} :: W_)) % (7 :: W_)) < (3 :: W_)) {" + emit " goto left${stage};" + emit " }" + emit " goto right${stage};" + emit + + emit "left${stage}:" + emit " acc = acc + (${k3} :: W_);" + emit " mix = mix + (${k4} :: W_);" + emit " goto join${stage};" + emit + + emit "right${stage}:" + emit " acc = acc + (${k4} :: W_);" + emit " mix = mix + (${k3} :: W_);" + emit " goto join${stage};" + emit + + emit "join${stage}:" + emit " acc = acc + mix + (${k1} :: W_);" + if (( next_stage == STAGES || next_stage % LOOP_PERIOD == 0 )); then + emit " goto latch${chunk};" + else + emit " goto split${next_stage};" + fi + emit + done + + for ((chunk = 0; chunk < chunk_count; chunk++)); do + loop_start=$(( chunk * LOOP_PERIOD )) + next_stage=$(( (chunk + 1) * LOOP_PERIOD )) + latch_mix=$(( 1000000 + chunk )) + latch_acc=$(( 2000000 + chunk )) + + emit "latch${chunk}:" + emit " trip${chunk} = trip${chunk} + (1 :: W_);" + emit " mix = mix + (${latch_mix} :: W_);" + emit " acc = acc + (${latch_acc} :: W_);" + emit " if (trip${chunk} < (2 :: W_)) {" + emit " goto split${loop_start};" + emit " }" + if (( next_stage < STAGES )); then + emit " goto split${next_stage};" + else + emit " return (acc);" + fi + emit + done + + emit "}" +} > "$OUT" View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/80120e480e5eca1c31fc5ece1eccaa9... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/80120e480e5eca1c31fc5ece1eccaa9... 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)
-
Simon Jakobi (@sjakobi)