@@ -28,8 +28,13 @@ import Data.IntMap (IntMap)
2828-- UseMap maps names to the set of used (reachable) argument positions.
2929type UseMap = Map Name IntSet
3030
31−-- DepMap maps functions (only functions) to their Deps.
32−type DepMap = Map Name Deps
31+-- Deps augmented with cached info.
32+-- fst = deps
33+-- snd = all names that the function depends on
34+type Deps' = (Deps, Set Name)
35+
36+-- DepMap maps functions (only functions) to their Deps'.
37+type DepMap = Map Name Deps'
3338
3439-- Deps of a function is a map from argument index
3540-- to all usages of the argument, including conditions
@@ -54,8 +59,24 @@ type PatVar = Ctors -> Var
5459type PatVars = Map Name PatVar
5560
5661findUsed :: Context -> Ctxt CGInfo -> [Name] -> DepMap
57−findUsed ctx cg ns = M.fromList [(n, getDeps n) | n <- ns]
62+findUsed ctx cg ns = dfs M.empty ns
5863 where
64+ dfs :: DepMap -> [Name] -> DepMap
65+ dfs dmap [] = dmap
66+ dfs dmap (n : ns)
67+ | n `M.member` dmap = dfs dmap ns
68+ | otherwise = dfs (M.insert n (deps, depn) dmap) ns
69+ where
70+ next = [n | n <- S.toList depn, n `M.notMember` dmap]
71+ depn = depNames deps
72+ deps = getDeps n
73+
74+ depNames :: Deps -> Set Name
75+ depNames = S.unions . map (S.unions . map f . S.toList) . IM.elems
76+ where
77+ f :: (Ctors, Cond) -> Set Name
78+ f (ctors, cond) = S.map fst cond -- let's ignore ctors for now
79+
5980 getDeps :: Name -> Deps
6081 getDeps n = case lookupDef n ctx of
6182 [def] -> getDepsDef def