2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[SimplCore]{Driver for simplifying @Core@ programs}
7 module SimplCore ( core2core ) where
9 #include "HsVersions.h"
11 import CmdLineOpts ( CoreToDo(..), SimplifierSwitch(..),
12 SwitchResult(..), intSwitchSet,
13 opt_D_dump_occur_anal, opt_D_dump_rules,
14 opt_D_dump_simpl_iterations,
15 opt_D_dump_simpl_stats,
17 opt_D_verbose_core2core,
18 opt_D_dump_occur_anal,
21 import CoreLint ( beginPass, endPass )
23 import CSE ( cseProgram )
24 import Rules ( RuleBase, ProtoCoreRule(..), pprProtoCoreRule, prepareLocalRuleBase,
25 prepareOrphanRuleBase, unionRuleBase, localRule )
27 import PprCore ( pprCoreBindings )
28 import OccurAnal ( occurAnalyseBinds )
29 import CoreUtils ( exprIsTrivial, etaReduceExpr, coreBindsSize )
30 import Simplify ( simplTopBinds, simplExpr )
31 import SimplUtils ( simplBinders )
33 import ErrUtils ( dumpIfSet )
34 import FloatIn ( floatInwards )
35 import FloatOut ( floatOutwards )
36 import Id ( isDataConWrapId )
38 import LiberateCase ( liberateCase )
39 import SAT ( doStaticArgs )
40 import Specialise ( specProgram)
41 import UsageSPInf ( doUsageSPInf )
42 import StrictAnal ( saBinds )
43 import WorkWrap ( wwTopBinds )
44 import CprAnalyse ( cprAnalyse )
46 import UniqSupply ( UniqSupply, mkSplitUniqSupply, splitUniqSupply )
47 import IO ( hPutStr, stderr )
50 import List ( partition )
53 %************************************************************************
55 \subsection{The driver for the simplifier}
57 %************************************************************************
60 core2core :: [CoreToDo] -- Spec of what core-to-core passes to do
61 -> [CoreBind] -- Binds in
62 -> [ProtoCoreRule] -- Rules in
63 -> IO ([CoreBind], RuleBase) -- binds, local orphan rules out
65 core2core core_todos binds rules
67 us <- mkSplitUniqSupply 's'
68 let (cp_us, ru_us) = splitUniqSupply us
70 let (local_rules, imported_rules) = partition localRule rules
72 better_local_rules <- simplRules ru_us local_rules binds
74 let (binds1, local_rule_base) = prepareLocalRuleBase binds better_local_rules
75 imported_rule_base = prepareOrphanRuleBase imported_rules
77 -- Do the main business
78 (stats, processed_binds, processed_local_rules)
79 <- doCorePasses zeroSimplCount cp_us binds1 local_rule_base
80 imported_rule_base Nothing core_todos
82 dumpIfSet opt_D_dump_simpl_stats
83 "Grand total simplifier statistics"
87 -- We only return local orphan rules, i.e., local rules not attached to an Id
88 return (processed_binds, processed_local_rules)
91 doCorePasses :: SimplCount -- simplifier stats
92 -> UniqSupply -- uniques
93 -> [CoreBind] -- local binds in (with rules attached)
94 -> RuleBase -- local orphan rules
95 -> RuleBase -- imported and builtin rules
96 -> Maybe RuleBase -- combined rulebase, or Nothing to ask for it to be rebuilt
97 -> [CoreToDo] -- which passes to do
98 -> IO (SimplCount, [CoreBind], RuleBase) -- stats, binds, local orphan rules
100 doCorePasses stats us binds lrb irb rb0 []
101 = return (stats, binds, lrb)
103 doCorePasses stats us binds lrb irb rb0 (to_do : to_dos)
105 let (us1, us2) = splitUniqSupply us
107 -- recompute rulebase if necessary
108 let rb = maybe (irb `unionRuleBase` lrb) id rb0
110 (stats1, binds1, mlrb1) <- doCorePass us1 binds lrb rb to_do
112 -- request rulebase recomputation if pass returned a new local rulebase
113 let (lrb1,rb1) = maybe (lrb, Just rb) (\ lrb1 -> (lrb1, Nothing)) mlrb1
115 doCorePasses (stats `plusSimplCount` stats1) us2 binds1 lrb1 irb rb1 to_dos
117 doCorePass us binds lrb rb (CoreDoSimplify sw_chkr) = _scc_ "Simplify" simplifyPgm rb sw_chkr us binds
118 doCorePass us binds lrb rb CoreCSE = _scc_ "CommonSubExpr" noStats (cseProgram binds)
119 doCorePass us binds lrb rb CoreLiberateCase = _scc_ "LiberateCase" noStats (liberateCase binds)
120 doCorePass us binds lrb rb CoreDoFloatInwards = _scc_ "FloatInwards" noStats (floatInwards binds)
121 doCorePass us binds lrb rb (CoreDoFloatOutwards f) = _scc_ "FloatOutwards" noStats (floatOutwards f us binds)
122 doCorePass us binds lrb rb CoreDoStaticArgs = _scc_ "StaticArgs" noStats (doStaticArgs us binds)
123 doCorePass us binds lrb rb CoreDoStrictness = _scc_ "Stranal" noStats (saBinds binds)
124 doCorePass us binds lrb rb CoreDoWorkerWrapper = _scc_ "WorkWrap" noStats (wwTopBinds us binds)
125 doCorePass us binds lrb rb CoreDoSpecialising = _scc_ "Specialise" noStats (specProgram us binds)
126 doCorePass us binds lrb rb CoreDoCPResult = _scc_ "CPResult" noStats (cprAnalyse binds)
127 doCorePass us binds lrb rb CoreDoPrintCore = _scc_ "PrintCore" noStats (printCore binds)
128 doCorePass us binds lrb rb CoreDoUSPInf
129 = _scc_ "CoreUsageSPInf"
130 if opt_UsageSPOn then
132 (binds1, rules1) <- doUsageSPInf us binds lrb
133 return (zeroSimplCount, binds1, rules1)
135 trace "WARNING: ignoring requested -fusagesp pass; requires -fusagesp-on" $
136 return (zeroSimplCount, binds, Nothing)
138 printCore binds = do dumpIfSet True "Print Core"
139 (pprCoreBindings binds)
142 -- most passes return no stats and don't change rules
143 noStats thing = do { binds <- thing; return (zeroSimplCount, binds, Nothing) }
147 %************************************************************************
149 \subsection{Dealing with rules}
151 %************************************************************************
153 We must do some gentle simplifiation on the template (but not the RHS)
154 of each rule. The case that forced me to add this was the fold/build rule,
155 which without simplification looked like:
156 fold k z (build (/\a. g a)) ==> ...
157 This doesn't match unless you do eta reduction on the build argument.
160 simplRules :: UniqSupply -> [ProtoCoreRule] -> [CoreBind] -> IO [ProtoCoreRule]
161 simplRules us rules binds
162 = do let (better_rules,_) = initSmpl sw_chkr us bind_vars black_list_all (mapSmpl simplRule rules)
164 dumpIfSet opt_D_dump_rules
165 "Transformation rules"
166 (vcat (map pprProtoCoreRule better_rules))
170 black_list_all v = not (isDataConWrapId v)
171 -- This stops all inlining except the
172 -- wrappers for data constructors
174 sw_chkr any = SwBool False -- A bit bogus
176 -- Boringly, we need to gather the in-scope set.
177 -- Typically this thunk won't even be force, but the test in
178 -- simpVar fails if it isn't right, and it might conceivably matter
179 bind_vars = foldr (unionVarSet . mkVarSet . bindersOf) emptyVarSet binds
182 simplRule rule@(ProtoCoreRule is_local id (BuiltinRule _))
184 simplRule rule@(ProtoCoreRule is_local id (Rule name bndrs args rhs))
186 = returnSmpl rule -- No need to fiddle with imported rules
188 = simplBinders bndrs $ \ bndrs' ->
189 mapSmpl simpl_arg args `thenSmpl` \ args' ->
190 simplExpr rhs `thenSmpl` \ rhs' ->
191 returnSmpl (ProtoCoreRule is_local id (Rule name bndrs' args' rhs'))
194 -- I've seen rules in which a LHS like
195 -- augment g (build h)
197 -- augment (\a. g a) (build h)
198 -- So it's a help to eta-reduce the args as we simplify them.
199 -- Otherwise we don't match when given an argument like
201 = simplExpr e `thenSmpl` \ e' ->
202 returnSmpl (etaReduceExpr e')
205 %************************************************************************
207 \subsection{The driver for the simplifier}
209 %************************************************************************
212 simplifyPgm :: RuleBase
213 -> (SimplifierSwitch -> SwitchResult)
215 -> [CoreBind] -- Input
216 -> IO (SimplCount, [CoreBind], Maybe RuleBase) -- New bindings
218 simplifyPgm (imported_rule_ids, rule_lhs_fvs)
221 beginPass "Simplify";
223 -- Glom all binds together in one Rec, in case any
224 -- transformations have introduced any new dependencies
226 -- NB: the global invariant is this:
227 -- *** the top level bindings are never cloned, and are always unique ***
229 -- We sort them into dependency order, but applying transformation rules may
230 -- make something at the top refer to something at the bottom:
234 -- RULE: p (q x) = h x
236 -- Applying this rule makes f refer to h, although it doesn't appear to in the
237 -- source program. Our solution is to do this occasional glom-together step,
238 -- just once per overall simplfication step.
240 let { recd_binds = [Rec (flattenBinds binds)] };
242 (termination_msg, it_count, counts_out, binds') <- iteration us 1 zeroSimplCount recd_binds;
244 dumpIfSet (opt_D_verbose_core2core && opt_D_dump_simpl_stats)
245 "Simplifier statistics"
246 (vcat [text termination_msg <+> text "after" <+> ppr it_count <+> text "iterations",
248 pprSimplCount counts_out]);
251 (opt_D_verbose_core2core && not opt_D_dump_simpl_iterations)
254 return (counts_out, binds', Nothing)
257 max_iterations = getSimplIntSwitch sw_chkr MaxSimplifierIterations
258 black_list_fn = blackListed rule_lhs_fvs (intSwitchSet sw_chkr SimplInlinePhase)
260 iteration us iteration_no counts binds
261 -- Try and force thunks off the binds; significantly reduces
262 -- space usage, especially with -O. JRS, 000620.
263 | let sz = coreBindsSize binds in sz == sz
265 -- Occurrence analysis
266 let { tagged_binds = _scc_ "OccAnal" occurAnalyseBinds binds } ;
268 dumpIfSet opt_D_dump_occur_anal "Occurrence analysis"
269 (pprCoreBindings tagged_binds);
272 -- We do this with a *case* not a *let* because lazy pattern
273 -- matching bit us with bad space leak!
274 -- With a let, we ended up with
279 -- case t of {(_,counts') -> if counts'=0 then ...
280 -- So the conditional didn't force counts', because the
281 -- selection got duplicated. Sigh!
282 case initSmpl sw_chkr us1 imported_rule_ids black_list_fn
283 (simplTopBinds tagged_binds)
284 of { (binds', counts') -> do {
285 -- The imported_rule_ids are used by initSmpl to initialise
286 -- the in-scope set. That way, the simplifier will change any
287 -- occurrences of the imported id to the one in the imported_rule_ids
288 -- set, which are decorated with their rules.
290 let { all_counts = counts `plusSimplCount` counts' } ;
292 -- Stop if nothing happened; don't dump output
293 if isZeroSimplCount counts' then
294 return ("Simplifier reached fixed point", iteration_no, all_counts, binds')
297 -- Dump the result of this iteration
298 dumpIfSet opt_D_dump_simpl_iterations
299 ("Simplifier iteration " ++ show iteration_no
300 ++ " out of " ++ show max_iterations)
301 (pprSimplCount counts') ;
303 if opt_D_dump_simpl_iterations then
304 endPass ("Simplifier iteration " ++ show iteration_no ++ " result")
305 opt_D_verbose_core2core
310 -- Stop if we've run out of iterations
311 if iteration_no == max_iterations then
314 if max_iterations > 2 then
315 hPutStr stderr ("NOTE: Simplifier still going after " ++
316 show max_iterations ++
317 " iterations; bailing out.\n")
322 return ("Simplifier baled out", iteration_no, all_counts, binds')
326 else iteration us2 (iteration_no + 1) all_counts binds'
329 (us1, us2) = splitUniqSupply us