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(..), switchIsOn, intSwitchSet,
13 opt_D_dump_occur_anal, opt_D_dump_rules,
14 opt_D_dump_simpl_iterations,
15 opt_D_dump_simpl_stats,
16 opt_D_dump_simpl, opt_D_dump_rules,
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, prepareRuleBase, orphanRule )
26 import PprCore ( pprCoreBindings )
27 import OccurAnal ( occurAnalyseBinds )
28 import CoreUtils ( exprIsTrivial, etaReduceExpr )
29 import Simplify ( simplTopBinds, simplExpr )
30 import SimplUtils ( findDefault, simplBinders )
32 import Literal ( Literal(..), literalType, mkMachInt )
33 import ErrUtils ( dumpIfSet )
34 import FloatIn ( floatInwards )
35 import FloatOut ( floatOutwards )
36 import Id ( Id, mkSysLocal, mkVanillaId, isBottomingId, isDataConWrapId,
37 idType, setIdType, idName, idInfo, setIdNoDiscard
41 import Module ( Module )
42 import Name ( mkLocalName, tidyOccName, tidyTopName,
43 NamedThing(..), OccName
45 import TyCon ( TyCon, isDataTyCon )
46 import PrelInfo ( unpackCStringId, unpackCString2Id, addr2IntegerId )
47 import PrelRules ( builtinRules )
50 tidyType, tidyTypes, tidyTopType, tidyTyVar, tidyTyVars,
53 import TysWiredIn ( smallIntegerDataCon, isIntegerTy )
54 import LiberateCase ( liberateCase )
55 import SAT ( doStaticArgs )
56 import Specialise ( specProgram)
57 import UsageSPInf ( doUsageSPInf )
58 import StrictAnal ( saBinds )
59 import WorkWrap ( wwTopBinds )
60 import CprAnalyse ( cprAnalyse )
62 import Unique ( Unique, Uniquable(..) )
63 import UniqSupply ( UniqSupply, mkSplitUniqSupply, splitUniqSupply, uniqFromSupply )
64 import Util ( mapAccumL )
65 import SrcLoc ( noSrcLoc )
68 import IO ( hPutStr, stderr )
71 import Ratio ( numerator, denominator )
74 %************************************************************************
76 \subsection{The driver for the simplifier}
78 %************************************************************************
81 core2core :: [CoreToDo] -- Spec of what core-to-core passes to do
82 -> [CoreBind] -- Binds in
83 -> [ProtoCoreRule] -- Rules
84 -> IO ([CoreBind], [ProtoCoreRule])
86 core2core core_todos binds rules
88 us <- mkSplitUniqSupply 's'
89 let (cp_us, us1) = splitUniqSupply us
90 (ru_us, ps_us) = splitUniqSupply us1
92 better_rules <- simplRules ru_us rules binds
94 let all_rules = builtinRules ++ better_rules
95 -- Here is where we add in the built-in rules
97 let (binds1, rule_base) = prepareRuleBase binds all_rules
99 -- Do the main business
100 (stats, processed_binds) <- doCorePasses zeroSimplCount cp_us binds1
103 dumpIfSet opt_D_dump_simpl_stats
104 "Grand total simplifier statistics"
105 (pprSimplCount stats)
108 return (processed_binds, filter orphanRule better_rules)
111 doCorePasses stats us binds irs []
112 = return (stats, binds)
114 doCorePasses stats us binds irs (to_do : to_dos)
116 let (us1, us2) = splitUniqSupply us
117 (stats1, binds1) <- doCorePass us1 binds irs to_do
118 doCorePasses (stats `plusSimplCount` stats1) us2 binds1 irs to_dos
120 doCorePass us binds rb (CoreDoSimplify sw_chkr) = _scc_ "Simplify" simplifyPgm rb sw_chkr us binds
121 doCorePass us binds rb CoreCSE = _scc_ "CommonSubExpr" noStats (cseProgram binds)
122 doCorePass us binds rb CoreLiberateCase = _scc_ "LiberateCase" noStats (liberateCase binds)
123 doCorePass us binds rb CoreDoFloatInwards = _scc_ "FloatInwards" noStats (floatInwards binds)
124 doCorePass us binds rb (CoreDoFloatOutwards f) = _scc_ "FloatOutwards" noStats (floatOutwards f us binds)
125 doCorePass us binds rb CoreDoStaticArgs = _scc_ "StaticArgs" noStats (doStaticArgs us binds)
126 doCorePass us binds rb CoreDoStrictness = _scc_ "Stranal" noStats (saBinds binds)
127 doCorePass us binds rb CoreDoWorkerWrapper = _scc_ "WorkWrap" noStats (wwTopBinds us binds)
128 doCorePass us binds rb CoreDoSpecialising = _scc_ "Specialise" noStats (specProgram us binds)
129 doCorePass us binds rb CoreDoCPResult = _scc_ "CPResult" noStats (cprAnalyse binds)
130 doCorePass us binds rb CoreDoPrintCore = _scc_ "PrintCore" noStats (printCore binds)
131 doCorePass us binds rb CoreDoUSPInf
132 = _scc_ "CoreUsageSPInf"
133 if opt_UsageSPOn then
134 noStats (doUsageSPInf us binds)
136 trace "WARNING: ignoring requested -fusagesp pass; requires -fusagesp-on" $
137 noStats (return binds)
139 printCore binds = do dumpIfSet True "Print Core"
140 (pprCoreBindings binds)
143 noStats thing = do { result <- thing; return (zeroSimplCount, result) }
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 (Rule name bndrs args rhs))
184 = returnSmpl rule -- No need to fiddle with imported rules
186 = simplBinders bndrs $ \ bndrs' ->
187 mapSmpl simpl_arg args `thenSmpl` \ args' ->
188 simplExpr rhs `thenSmpl` \ rhs' ->
189 returnSmpl (ProtoCoreRule is_local id (Rule name bndrs' args' rhs'))
192 -- I've seen rules in which a LHS like
193 -- augment g (build h)
195 -- augment (\a. g a) (build h)
196 -- So it's a help to eta-reduce the args as we simplify them.
197 -- Otherwise we don't match when given an argument like
199 = simplExpr e `thenSmpl` \ e' ->
200 returnSmpl (etaReduceExpr e')
203 %************************************************************************
205 \subsection{The driver for the simplifier}
207 %************************************************************************
210 simplifyPgm :: RuleBase
211 -> (SimplifierSwitch -> SwitchResult)
213 -> [CoreBind] -- Input
214 -> IO (SimplCount, [CoreBind]) -- New bindings
216 simplifyPgm (imported_rule_ids, rule_lhs_fvs)
219 beginPass "Simplify";
221 -- Glom all binds together in one Rec, in case any
222 -- transformations have introduced any new dependencies
224 -- NB: the global invariant is this:
225 -- *** the top level bindings are never cloned, and are always unique ***
227 -- We sort them into dependency order, but applying transformation rules may
228 -- make something at the top refer to something at the bottom:
232 -- RULE: p (q x) = h x
234 -- Applying this rule makes f refer to h, although it doesn't appear to in the
235 -- source program. Our solution is to do this occasional glom-together step,
236 -- just once per overall simplfication step.
238 let { recd_binds = [Rec (flattenBinds binds)] };
240 (termination_msg, it_count, counts_out, binds') <- iteration us 1 zeroSimplCount recd_binds;
242 dumpIfSet (opt_D_verbose_core2core && opt_D_dump_simpl_stats)
243 "Simplifier statistics"
244 (vcat [text termination_msg <+> text "after" <+> ppr it_count <+> text "iterations",
246 pprSimplCount counts_out]);
249 (opt_D_verbose_core2core && not opt_D_dump_simpl_iterations)
252 return (counts_out, binds')
255 max_iterations = getSimplIntSwitch sw_chkr MaxSimplifierIterations
256 black_list_fn = blackListed rule_lhs_fvs (intSwitchSet sw_chkr SimplInlinePhase)
258 core_iter_dump binds | opt_D_verbose_core2core = pprCoreBindings binds
261 iteration us iteration_no counts binds
263 -- Occurrence analysis
264 let { tagged_binds = _scc_ "OccAnal" occurAnalyseBinds binds } ;
266 dumpIfSet opt_D_dump_occur_anal "Occurrence analysis"
267 (pprCoreBindings tagged_binds);
270 let { (binds', counts') = initSmpl sw_chkr us1 imported_rule_ids
272 (simplTopBinds tagged_binds);
273 -- The imported_rule_ids are used by initSmpl to initialise
274 -- the in-scope set. That way, the simplifier will change any
275 -- occurrences of the imported id to the one in the imported_rule_ids
276 -- set, which are decorated with their rules.
278 all_counts = counts `plusSimplCount` counts'
281 -- Stop if nothing happened; don't dump output
282 if isZeroSimplCount counts' then
283 return ("Simplifier reached fixed point", iteration_no, all_counts, binds')
286 -- Dump the result of this iteration
287 dumpIfSet opt_D_dump_simpl_iterations
288 ("Simplifier iteration " ++ show iteration_no
289 ++ " out of " ++ show max_iterations)
290 (pprSimplCount counts') ;
292 if opt_D_dump_simpl_iterations then
293 endPass ("Simplifier iteration " ++ show iteration_no ++ " result")
294 opt_D_verbose_core2core
299 -- Stop if we've run out of iterations
300 if iteration_no == max_iterations then
303 if max_iterations > 2 then
304 hPutStr stderr ("NOTE: Simplifier still going after " ++
305 show max_iterations ++
306 " iterations; bailing out.\n")
311 return ("Simplifier baled out", iteration_no, all_counts, binds')
315 else iteration us2 (iteration_no + 1) all_counts binds'
318 (us1, us2) = splitUniqSupply us