Allow -ddump-simpl-phases to specify which phases to dump
[ghc-hetmet.git] / compiler / simplCore / SimplCore.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[SimplCore]{Driver for simplifying @Core@ programs}
5
6 \begin{code}
7 {-# OPTIONS -w #-}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 -- for details
13
14 module SimplCore ( core2core, simplifyExpr ) where
15
16 #include "HsVersions.h"
17
18 import DynFlags         ( CoreToDo(..), SimplifierSwitch(..),
19                           SimplifierMode(..), DynFlags, DynFlag(..), dopt,
20                           getCoreToDo, shouldDumpSimplPhase )
21 import CoreSyn
22 import HscTypes
23 import CSE              ( cseProgram )
24 import Rules            ( RuleBase, emptyRuleBase, mkRuleBase, unionRuleBase,
25                           extendRuleBaseList, pprRuleBase, ruleCheckProgram,
26                           addSpecInfo, addIdSpecialisations )
27 import PprCore          ( pprCoreBindings, pprCoreExpr, pprRules )
28 import OccurAnal        ( occurAnalysePgm, occurAnalyseExpr )
29 import IdInfo           ( setNewStrictnessInfo, newStrictnessInfo, 
30                           setWorkerInfo, workerInfo, setSpecInfoHead,
31                           setInlinePragInfo, inlinePragInfo,
32                           setSpecInfo, specInfo, specInfoRules )
33 import CoreUtils        ( coreBindsSize )
34 import Simplify         ( simplTopBinds, simplExpr )
35 import SimplEnv         ( SimplEnv, simplBinders, mkSimplEnv, setInScopeSet )
36 import SimplMonad
37 import ErrUtils         ( dumpIfSet, dumpIfSet_dyn, showPass )
38 import CoreLint         ( endPassIf, endIteration )
39 import FloatIn          ( floatInwards )
40 import FloatOut         ( floatOutwards )
41 import FamInstEnv
42 import Id
43 import DataCon
44 import TyCon            ( tyConSelIds, tyConDataCons )
45 import Class            ( classSelIds )
46 import VarSet
47 import VarEnv
48 import NameEnv          ( lookupNameEnv )
49 import LiberateCase     ( liberateCase )
50 import SAT              ( doStaticArgs )
51 import Specialise       ( specProgram)
52 import SpecConstr       ( specConstrProgram)
53 import DmdAnal          ( dmdAnalPgm )
54 import WorkWrap         ( wwTopBinds )
55 #ifdef OLD_STRICTNESS
56 import StrictAnal       ( saBinds )
57 import CprAnalyse       ( cprAnalyse )
58 #endif
59 import Vectorise        ( vectorise )
60
61 import UniqSupply       ( UniqSupply, mkSplitUniqSupply, splitUniqSupply )
62 import IO               ( hPutStr, stderr )
63 import Outputable
64 import List             ( partition )
65 import Maybes
66 \end{code}
67
68 %************************************************************************
69 %*                                                                      *
70 \subsection{The driver for the simplifier}
71 %*                                                                      *
72 %************************************************************************
73
74 \begin{code}
75 core2core :: HscEnv
76           -> ModGuts
77           -> IO ModGuts
78
79 core2core hsc_env guts
80   = do  {
81         ; let dflags = hsc_dflags hsc_env
82               core_todos = getCoreToDo dflags
83
84         ; us <- mkSplitUniqSupply 's'
85         ; let (cp_us, ru_us) = splitUniqSupply us
86
87                 -- COMPUTE THE RULE BASE TO USE
88         ; (imp_rule_base, guts1) <- prepareRules hsc_env guts ru_us
89
90                 -- Note [Injecting implicit bindings]
91         ; let implicit_binds = getImplicitBinds (mg_types guts1)
92               guts2 = guts1 { mg_binds = implicit_binds ++ mg_binds guts1 }
93
94                 -- DO THE BUSINESS
95         ; (stats, guts3) <- doCorePasses hsc_env imp_rule_base cp_us
96                                          (zeroSimplCount dflags) 
97                                          guts2 core_todos
98
99         ; dumpIfSet_dyn dflags Opt_D_dump_simpl_stats
100                   "Grand total simplifier statistics"
101                   (pprSimplCount stats)
102
103         ; return guts3 }
104
105
106 simplifyExpr :: DynFlags -- includes spec of what core-to-core passes to do
107              -> CoreExpr
108              -> IO CoreExpr
109 -- simplifyExpr is called by the driver to simplify an
110 -- expression typed in at the interactive prompt
111 simplifyExpr dflags expr
112   = do  {
113         ; showPass dflags "Simplify"
114
115         ; us <-  mkSplitUniqSupply 's'
116
117         ; let (expr', _counts) = initSmpl dflags emptyRuleBase emptyFamInstEnvs us $
118                                  simplExprGently gentleSimplEnv expr
119
120         ; dumpIfSet_dyn dflags Opt_D_dump_simpl "Simplified expression"
121                         (pprCoreExpr expr')
122
123         ; return expr'
124         }
125
126 gentleSimplEnv :: SimplEnv
127 gentleSimplEnv = mkSimplEnv SimplGently  (isAmongSimpl [])
128
129 doCorePasses :: HscEnv
130              -> RuleBase        -- the imported main rule base
131              -> UniqSupply      -- uniques
132              -> SimplCount      -- simplifier stats
133              -> ModGuts         -- local binds in (with rules attached)
134              -> [CoreToDo]      -- which passes to do
135              -> IO (SimplCount, ModGuts)
136
137 doCorePasses hsc_env rb us stats guts []
138   = return (stats, guts)
139
140 doCorePasses hsc_env rb us stats guts (CoreDoPasses to_dos1 : to_dos2) 
141   = doCorePasses hsc_env rb us stats guts (to_dos1 ++ to_dos2) 
142
143 doCorePasses hsc_env rb us stats guts (to_do : to_dos) 
144   = do
145         let (us1, us2) = splitUniqSupply us
146         (stats1, guts1) <- doCorePass to_do hsc_env us1 rb guts
147         doCorePasses hsc_env rb us2 (stats `plusSimplCount` stats1) guts1 to_dos
148
149 doCorePass :: CoreToDo -> HscEnv -> UniqSupply -> RuleBase
150            -> ModGuts -> IO (SimplCount, ModGuts)
151 doCorePass (CoreDoSimplify mode sws)   = {-# SCC "Simplify" #-}      simplifyPgm mode sws
152 doCorePass CoreCSE                     = {-# SCC "CommonSubExpr" #-} trBinds  cseProgram
153 doCorePass CoreLiberateCase            = {-# SCC "LiberateCase" #-}  liberateCase
154 doCorePass CoreDoFloatInwards          = {-# SCC "FloatInwards" #-}  trBinds  floatInwards
155 doCorePass (CoreDoFloatOutwards f)     = {-# SCC "FloatOutwards" #-} trBindsU (floatOutwards f)
156 doCorePass CoreDoStaticArgs            = {-# SCC "StaticArgs" #-}    trBinds  doStaticArgs
157 doCorePass CoreDoStrictness            = {-# SCC "Stranal" #-}       trBinds  dmdAnalPgm
158 doCorePass CoreDoWorkerWrapper         = {-# SCC "WorkWrap" #-}      trBindsU wwTopBinds
159 doCorePass CoreDoSpecialising          = {-# SCC "Specialise" #-}    trBindsU specProgram
160 doCorePass CoreDoSpecConstr            = {-# SCC "SpecConstr" #-}    trBindsU specConstrProgram
161 doCorePass CoreDoGlomBinds             = trBinds glomBinds
162 doCorePass CoreDoVectorisation         = {-# SCC "Vectorise" #-}     vectorise
163 doCorePass CoreDoPrintCore             = observe printCore
164 doCorePass (CoreDoRuleCheck phase pat) = ruleCheck phase pat
165 doCorePass CoreDoNothing               = observe (\ _ _ -> return ())
166 #ifdef OLD_STRICTNESS                  
167 doCorePass CoreDoOldStrictness         = {-# SCC "OldStrictness" #-} trBinds doOldStrictness
168 #else
169 doCorePass CoreDoOldStrictness         = panic "CoreDoOldStrictness"
170 #endif
171 doCorePass (CoreDoPasses _) = panic "CoreDoPasses"
172
173 #ifdef OLD_STRICTNESS
174 doOldStrictness dfs binds
175   = do binds1 <- saBinds dfs binds
176        binds2 <- cprAnalyse dfs binds1
177        return binds2
178 #endif
179
180 printCore _ binds = dumpIfSet True "Print Core" (pprCoreBindings binds)
181
182 ruleCheck phase pat hsc_env us rb guts 
183   =  do let dflags = hsc_dflags hsc_env
184         showPass dflags "RuleCheck"
185         printDump (ruleCheckProgram phase pat rb (mg_binds guts))
186         return (zeroSimplCount dflags, guts)
187
188 -- Most passes return no stats and don't change rules
189 trBinds :: (DynFlags -> [CoreBind] -> IO [CoreBind])
190         -> HscEnv -> UniqSupply -> RuleBase -> ModGuts
191         -> IO (SimplCount, ModGuts)
192 trBinds do_pass hsc_env us rb guts
193   = do  { binds' <- do_pass dflags (mg_binds guts)
194         ; return (zeroSimplCount dflags, guts { mg_binds = binds' }) }
195   where
196     dflags = hsc_dflags hsc_env
197
198 trBindsU :: (DynFlags -> UniqSupply -> [CoreBind] -> IO [CoreBind])
199         -> HscEnv -> UniqSupply -> RuleBase -> ModGuts
200         -> IO (SimplCount, ModGuts)
201 trBindsU do_pass hsc_env us rb guts
202   = do  { binds' <- do_pass dflags us (mg_binds guts)
203         ; return (zeroSimplCount dflags, guts { mg_binds = binds' }) }
204   where
205     dflags = hsc_dflags hsc_env
206
207 -- Observer passes just peek; don't modify the bindings at all
208 observe :: (DynFlags -> [CoreBind] -> IO a)
209         -> HscEnv -> UniqSupply -> RuleBase -> ModGuts
210         -> IO (SimplCount, ModGuts)
211 observe do_pass hsc_env us rb guts 
212   = do  { binds <- do_pass dflags (mg_binds guts)
213         ; return (zeroSimplCount dflags, guts) }
214   where
215     dflags = hsc_dflags hsc_env
216 \end{code}
217
218
219 %************************************************************************
220 %*                                                                      *
221         Implicit bindings
222 %*                                                                      *
223 %************************************************************************
224
225 Note [Injecting implicit bindings]
226 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
227 We used to inject the implict bindings right at the end, in CoreTidy.
228 But some of these bindings, notably record selectors, are not
229 constructed in an optimised form.  E.g. record selector for
230         data T = MkT { x :: {-# UNPACK #-} !Int }
231 Then the unfolding looks like
232         x = \t. case t of MkT x1 -> let x = I# x1 in x
233 This generates bad code unless it's first simplified a bit.
234 (Only matters when the selector is used curried; eg map x ys.)
235 See Trac #2070.
236
237 \begin{code}
238 getImplicitBinds :: TypeEnv -> [CoreBind]
239 getImplicitBinds type_env
240   = map get_defn (concatMap implicit_con_ids (typeEnvTyCons type_env)
241                   ++ concatMap other_implicit_ids (typeEnvElts type_env))
242         -- Put the constructor wrappers first, because
243         -- other implicit bindings (notably the fromT functions arising 
244         -- from generics) use the constructor wrappers.  At least that's
245         -- what External Core likes
246   where
247     implicit_con_ids tc = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
248     
249     other_implicit_ids (ATyCon tc) = filter (not . isNaughtyRecordSelector) (tyConSelIds tc)
250         -- The "naughty" ones are not real functions at all
251         -- They are there just so we can get decent error messages
252         -- See Note  [Naughty record selectors] in MkId.lhs
253     other_implicit_ids (AClass cl) = classSelIds cl
254     other_implicit_ids _other      = []
255     
256     get_defn :: Id -> CoreBind
257     get_defn id = NonRec id (unfoldingTemplate (idUnfolding id))
258 \end{code}
259
260
261 %************************************************************************
262 %*                                                                      *
263         Dealing with rules
264 %*                                                                      *
265 %************************************************************************
266
267 -- prepareLocalRuleBase takes the CoreBinds and rules defined in this module.
268 -- It attaches those rules that are for local Ids to their binders, and
269 -- returns the remainder attached to Ids in an IdSet.  
270
271 \begin{code}
272 prepareRules :: HscEnv 
273              -> ModGuts
274              -> UniqSupply
275              -> IO (RuleBase,           -- Rule base for imported things, incl
276                                         -- (a) rules defined in this module (orphans)
277                                         -- (b) rules from other modules in home package
278                                         -- but not things from other packages
279
280                     ModGuts)            -- Modified fields are 
281                                         --      (a) Bindings have rules attached,
282                                         --      (b) Rules are now just orphan rules
283
284 prepareRules hsc_env@(HscEnv { hsc_dflags = dflags, hsc_HPT = hpt })
285              guts@(ModGuts { mg_binds = binds, mg_deps = deps, mg_rules = local_rules })
286              us 
287   = do  { let   -- Simplify the local rules; boringly, we need to make an in-scope set
288                 -- from the local binders, to avoid warnings from Simplify.simplVar
289               local_ids        = mkInScopeSet (mkVarSet (bindersOfBinds binds))
290               env              = setInScopeSet gentleSimplEnv local_ids 
291               (better_rules,_) = initSmpl dflags emptyRuleBase emptyFamInstEnvs us $
292                                  (mapM (simplRule env) local_rules)
293               home_pkg_rules   = hptRules hsc_env (dep_mods deps)
294
295                 -- Find the rules for locally-defined Ids; then we can attach them
296                 -- to the binders in the top-level bindings
297                 -- 
298                 -- Reason
299                 --      - It makes the rules easier to look up
300                 --      - It means that transformation rules and specialisations for
301                 --        locally defined Ids are handled uniformly
302                 --      - It keeps alive things that are referred to only from a rule
303                 --        (the occurrence analyser knows about rules attached to Ids)
304                 --      - It makes sure that, when we apply a rule, the free vars
305                 --        of the RHS are more likely to be in scope
306                 --      - The imported rules are carried in the in-scope set
307                 --        which is extended on each iteration by the new wave of
308                 --        local binders; any rules which aren't on the binding will
309                 --        thereby get dropped
310               (rules_for_locals, rules_for_imps) = partition isLocalRule better_rules
311               local_rule_base = extendRuleBaseList emptyRuleBase rules_for_locals
312               binds_w_rules   = updateBinders local_rule_base binds
313
314               hpt_rule_base = mkRuleBase home_pkg_rules
315               imp_rule_base = extendRuleBaseList hpt_rule_base rules_for_imps
316
317         ; dumpIfSet_dyn dflags Opt_D_dump_rules "Transformation rules"
318                 (vcat [text "Local rules", pprRules better_rules,
319                        text "",
320                        text "Imported rules", pprRuleBase imp_rule_base])
321
322         ; return (imp_rule_base, guts { mg_binds = binds_w_rules, 
323                                         mg_rules = rules_for_imps })
324     }
325
326 updateBinders :: RuleBase -> [CoreBind] -> [CoreBind]
327 updateBinders local_rules binds
328   = map update_bndrs binds
329   where
330     update_bndrs (NonRec b r) = NonRec (update_bndr b) r
331     update_bndrs (Rec prs)    = Rec [(update_bndr b, r) | (b,r) <- prs]
332
333     update_bndr bndr = case lookupNameEnv local_rules (idName bndr) of
334                           Nothing    -> bndr
335                           Just rules -> bndr `addIdSpecialisations` rules
336                                 -- The binder might have some existing rules,
337                                 -- arising from specialisation pragmas
338 \end{code}
339
340
341 We must do some gentle simplification on the template (but not the RHS)
342 of each rule.  The case that forced me to add this was the fold/build rule,
343 which without simplification looked like:
344         fold k z (build (/\a. g a))  ==>  ...
345 This doesn't match unless you do eta reduction on the build argument.
346
347 \begin{code}
348 simplRule env rule@(BuiltinRule {})
349   = return rule
350 simplRule env rule@(Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs })
351   = do (env, bndrs') <- simplBinders env bndrs
352        args' <- mapM (simplExprGently env) args
353        rhs' <- simplExprGently env rhs
354        return (rule { ru_bndrs = bndrs', ru_args = args', ru_rhs = rhs' })
355
356 -- It's important that simplExprGently does eta reduction.
357 -- For example, in a rule like:
358 --      augment g (build h) 
359 -- we do not want to get
360 --      augment (\a. g a) (build h)
361 -- otherwise we don't match when given an argument like
362 --      (\a. h a a)
363 --
364 -- The simplifier does indeed do eta reduction (it's in
365 -- Simplify.completeLam) but only if -O is on.
366 \end{code}
367
368 \begin{code}
369 simplExprGently :: SimplEnv -> CoreExpr -> SimplM CoreExpr
370 -- Simplifies an expression 
371 --      does occurrence analysis, then simplification
372 --      and repeats (twice currently) because one pass
373 --      alone leaves tons of crud.
374 -- Used (a) for user expressions typed in at the interactive prompt
375 --      (b) the LHS and RHS of a RULE
376 --
377 -- The name 'Gently' suggests that the SimplifierMode is SimplGently,
378 -- and in fact that is so.... but the 'Gently' in simplExprGently doesn't
379 -- enforce that; it just simplifies the expression twice
380
381 simplExprGently env expr = do
382     expr1 <- simplExpr env (occurAnalyseExpr expr)
383     simplExpr env (occurAnalyseExpr expr1)
384 \end{code}
385
386
387 %************************************************************************
388 %*                                                                      *
389 \subsection{Glomming}
390 %*                                                                      *
391 %************************************************************************
392
393 \begin{code}
394 glomBinds :: DynFlags -> [CoreBind] -> IO [CoreBind]
395 -- Glom all binds together in one Rec, in case any
396 -- transformations have introduced any new dependencies
397 --
398 -- NB: the global invariant is this:
399 --      *** the top level bindings are never cloned, and are always unique ***
400 --
401 -- We sort them into dependency order, but applying transformation rules may
402 -- make something at the top refer to something at the bottom:
403 --      f = \x -> p (q x)
404 --      h = \y -> 3
405 --      
406 --      RULE:  p (q x) = h x
407 --
408 -- Applying this rule makes f refer to h, 
409 -- although it doesn't appear to in the source program.  
410 -- This pass lets us control where it happens.
411 --
412 -- NOTICE that this cannot happen for rules whose head is a locally-defined
413 -- function.  It only happens for rules whose head is an imported function
414 -- (p in the example above).  So, for example, the rule had been
415 --      RULE: f (p x) = h x
416 -- then the rule for f would be attached to f itself (in its IdInfo) 
417 -- by prepareLocalRuleBase and h would be regarded by the occurrency 
418 -- analyser as free in f.
419
420 glomBinds dflags binds
421   = do { showPass dflags "GlomBinds" ;
422          let { recd_binds = [Rec (flattenBinds binds)] } ;
423          return recd_binds }
424         -- Not much point in printing the result... 
425         -- just consumes output bandwidth
426 \end{code}
427
428
429 %************************************************************************
430 %*                                                                      *
431 \subsection{The driver for the simplifier}
432 %*                                                                      *
433 %************************************************************************
434
435 \begin{code}
436 simplifyPgm :: SimplifierMode
437             -> [SimplifierSwitch]
438             -> HscEnv
439             -> UniqSupply
440             -> RuleBase
441             -> ModGuts
442             -> IO (SimplCount, ModGuts)  -- New bindings
443
444 simplifyPgm mode switches hsc_env us imp_rule_base guts
445   = do {
446         showPass dflags "Simplify";
447
448         (termination_msg, it_count, counts_out, binds') 
449            <- do_iteration us 1 (zeroSimplCount dflags) (mg_binds guts) ;
450
451         dumpIfSet (dump_phase && dopt Opt_D_dump_simpl_stats dflags)
452                   "Simplifier statistics"
453                   (vcat [text termination_msg <+> text "after" <+> ppr it_count <+> text "iterations",
454                          text "",
455                          pprSimplCount counts_out]);
456
457         endPassIf dump_phase dflags
458                   ("Simplify phase " ++ phase_info ++ " done")
459                   Opt_D_dump_simpl_phases binds';
460
461         return (counts_out, guts { mg_binds = binds' })
462     }
463   where
464     dflags         = hsc_dflags hsc_env
465     phase_info     = case mode of
466                           SimplGently  -> "gentle"
467                           SimplPhase n -> show n
468
469     dump_phase     = shouldDumpSimplPhase dflags mode
470                    
471     sw_chkr        = isAmongSimpl switches
472     max_iterations = intSwitchSet sw_chkr MaxSimplifierIterations `orElse` 2
473  
474     do_iteration us iteration_no counts binds
475         -- iteration_no is the number of the iteration we are
476         -- about to begin, with '1' for the first
477       | iteration_no > max_iterations   -- Stop if we've run out of iterations
478       = do {
479 #ifdef DEBUG
480             if  max_iterations > 2 then
481                 hPutStr stderr ("NOTE: Simplifier still going after " ++ 
482                                 show max_iterations ++ 
483                                 " iterations; bailing out.  Size = " ++ show (coreBindsSize binds) ++ "\n" )
484             else 
485                 return ();
486 #endif
487                 -- Subtract 1 from iteration_no to get the
488                 -- number of iterations we actually completed
489             return ("Simplifier baled out", iteration_no - 1, counts, binds)
490         }
491
492       -- Try and force thunks off the binds; significantly reduces
493       -- space usage, especially with -O.  JRS, 000620.
494       | let sz = coreBindsSize binds in sz == sz
495       = do {
496                 -- Occurrence analysis
497            let { tagged_binds = {-# SCC "OccAnal" #-} occurAnalysePgm binds } ;
498            dumpIfSet_dyn dflags Opt_D_dump_occur_anal "Occurrence analysis"
499                      (pprCoreBindings tagged_binds);
500
501                 -- Get any new rules, and extend the rule base
502                 -- We need to do this regularly, because simplification can
503                 -- poke on IdInfo thunks, which in turn brings in new rules
504                 -- behind the scenes.  Otherwise there's a danger we'll simply
505                 -- miss the rules for Ids hidden inside imported inlinings
506            eps <- hscEPS hsc_env ;
507            let  { rule_base' = unionRuleBase imp_rule_base (eps_rule_base eps)
508                 ; simpl_env  = mkSimplEnv mode sw_chkr 
509                 ; simpl_binds = {-# SCC "SimplTopBinds" #-} 
510                                 simplTopBinds simpl_env tagged_binds
511                 ; fam_envs = (eps_fam_inst_env eps, mg_fam_inst_env guts) } ;
512            
513                 -- Simplify the program
514                 -- We do this with a *case* not a *let* because lazy pattern
515                 -- matching bit us with bad space leak!
516                 -- With a let, we ended up with
517                 --   let
518                 --      t = initSmpl ...
519                 --      counts' = snd t
520                 --   in
521                 --      case t of {(_,counts') -> if counts'=0 then ... }
522                 -- So the conditional didn't force counts', because the
523                 -- selection got duplicated.  Sigh!
524            case initSmpl dflags rule_base' fam_envs us1 simpl_binds of {
525                 (binds', counts') -> do {
526
527            let  { all_counts = counts `plusSimplCount` counts'
528                 ; herald     = "Simplifier phase " ++ phase_info ++ 
529                               ", iteration " ++ show iteration_no ++
530                               " out of " ++ show max_iterations
531                 } ;
532
533                 -- Stop if nothing happened; don't dump output
534            if isZeroSimplCount counts' then
535                 return ("Simplifier reached fixed point", iteration_no, 
536                         all_counts, binds')
537            else do {
538                 -- Short out indirections
539                 -- We do this *after* at least one run of the simplifier 
540                 -- because indirection-shorting uses the export flag on *occurrences*
541                 -- and that isn't guaranteed to be ok until after the first run propagates
542                 -- stuff from the binding site to its occurrences
543                 --
544                 -- ToDo: alas, this means that indirection-shorting does not happen at all
545                 --       if the simplifier does nothing (not common, I know, but unsavoury)
546            let { binds'' = {-# SCC "ZapInd" #-} shortOutIndirections binds' } ;
547
548                 -- Dump the result of this iteration
549            dumpIfSet_dyn dflags Opt_D_dump_simpl_iterations herald
550                          (pprSimplCount counts') ;
551            endIteration dflags herald Opt_D_dump_simpl_iterations binds'' ;
552
553                 -- Loop
554            do_iteration us2 (iteration_no + 1) all_counts binds''
555         }  } } }
556       where
557           (us1, us2) = splitUniqSupply us
558 \end{code}
559
560
561 %************************************************************************
562 %*                                                                      *
563                 Shorting out indirections
564 %*                                                                      *
565 %************************************************************************
566
567 If we have this:
568
569         x_local = <expression>
570         ...bindings...
571         x_exported = x_local
572
573 where x_exported is exported, and x_local is not, then we replace it with this:
574
575         x_exported = <expression>
576         x_local = x_exported
577         ...bindings...
578
579 Without this we never get rid of the x_exported = x_local thing.  This
580 save a gratuitous jump (from \tr{x_exported} to \tr{x_local}), and
581 makes strictness information propagate better.  This used to happen in
582 the final phase, but it's tidier to do it here.
583
584 STRICTNESS: if we have done strictness analysis, we want the strictness info on
585 x_local to transfer to x_exported.  Hence the copyIdInfo call.
586
587 RULES: we want to *add* any RULES for x_local to x_exported.
588
589 Note [Rules and indirection-zapping]
590 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
591 Problem: what if x_exported has a RULE that mentions something in ...bindings...?
592 Then the things mentioned can be out of scope!  Solution
593  a) Make sure that in this pass the usage-info from x_exported is 
594         available for ...bindings...
595  b) If there are any such RULES, rec-ify the entire top-level. 
596     It'll get sorted out next time round
597
598 Messing up the rules
599 ~~~~~~~~~~~~~~~~~~~~
600 The example that went bad on me at one stage was this one:
601         
602     iterate :: (a -> a) -> a -> [a]
603         [Exported]
604     iterate = iterateList       
605     
606     iterateFB c f x = x `c` iterateFB c f (f x)
607     iterateList f x =  x : iterateList f (f x)
608         [Not exported]
609     
610     {-# RULES
611     "iterate"   forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
612     "iterateFB"                 iterateFB (:) = iterateList
613      #-}
614
615 This got shorted out to:
616
617     iterateList :: (a -> a) -> a -> [a]
618     iterateList = iterate
619     
620     iterateFB c f x = x `c` iterateFB c f (f x)
621     iterate f x =  x : iterate f (f x)
622     
623     {-# RULES
624     "iterate"   forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
625     "iterateFB"                 iterateFB (:) = iterate
626      #-}
627
628 And now we get an infinite loop in the rule system 
629         iterate f x -> build (\cn -> iterateFB c f x)
630                     -> iterateFB (:) f x
631                     -> iterate f x
632
633 Tiresome old solution: 
634         don't do shorting out if f has rewrite rules (see shortableIdInfo)
635
636 New solution (I think): 
637         use rule switching-off pragmas to get rid 
638         of iterateList in the first place
639
640
641 Other remarks
642 ~~~~~~~~~~~~~
643 If more than one exported thing is equal to a local thing (i.e., the
644 local thing really is shared), then we do one only:
645 \begin{verbatim}
646         x_local = ....
647         x_exported1 = x_local
648         x_exported2 = x_local
649 ==>
650         x_exported1 = ....
651
652         x_exported2 = x_exported1
653 \end{verbatim}
654
655 We rely on prior eta reduction to simplify things like
656 \begin{verbatim}
657         x_exported = /\ tyvars -> x_local tyvars
658 ==>
659         x_exported = x_local
660 \end{verbatim}
661 Hence,there's a possibility of leaving unchanged something like this:
662 \begin{verbatim}
663         x_local = ....
664         x_exported1 = x_local Int
665 \end{verbatim}
666 By the time we've thrown away the types in STG land this 
667 could be eliminated.  But I don't think it's very common
668 and it's dangerous to do this fiddling in STG land 
669 because we might elminate a binding that's mentioned in the
670 unfolding for something.
671
672 \begin{code}
673 type IndEnv = IdEnv Id          -- Maps local_id -> exported_id
674
675 shortOutIndirections :: [CoreBind] -> [CoreBind]
676 shortOutIndirections binds
677   | isEmptyVarEnv ind_env = binds
678   | no_need_to_flatten    = binds'                      -- See Note [Rules and indirect-zapping]
679   | otherwise             = [Rec (flattenBinds binds')] -- for this no_need_to_flatten stuff
680   where
681     ind_env            = makeIndEnv binds
682     exp_ids            = varSetElems ind_env    -- These exported Ids are the subjects
683     exp_id_set         = mkVarSet exp_ids       -- of the indirection-elimination
684     no_need_to_flatten = all (null . specInfoRules . idSpecialisation) exp_ids
685     binds'             = concatMap zap binds
686
687     zap (NonRec bndr rhs) = [NonRec b r | (b,r) <- zapPair (bndr,rhs)]
688     zap (Rec pairs)       = [Rec (concatMap zapPair pairs)]
689
690     zapPair (bndr, rhs)
691         | bndr `elemVarSet` exp_id_set             = []
692         | Just exp_id <- lookupVarEnv ind_env bndr = [(transferIdInfo exp_id bndr, rhs),
693                                                       (bndr, Var exp_id)]
694         | otherwise                                = [(bndr,rhs)]
695                              
696 makeIndEnv :: [CoreBind] -> IndEnv
697 makeIndEnv binds
698   = foldr add_bind emptyVarEnv binds
699   where
700     add_bind :: CoreBind -> IndEnv -> IndEnv
701     add_bind (NonRec exported_id rhs) env = add_pair (exported_id, rhs) env
702     add_bind (Rec pairs)              env = foldr add_pair env pairs
703
704     add_pair :: (Id,CoreExpr) -> IndEnv -> IndEnv
705     add_pair (exported_id, Var local_id) env
706         | shortMeOut env exported_id local_id = extendVarEnv env local_id exported_id
707     add_pair (exported_id, rhs) env
708         = env
709                         
710 shortMeOut ind_env exported_id local_id
711 -- The if-then-else stuff is just so I can get a pprTrace to see
712 -- how often I don't get shorting out becuase of IdInfo stuff
713   = if isExportedId exported_id &&              -- Only if this is exported
714
715        isLocalId local_id &&                    -- Only if this one is defined in this
716                                                 --      module, so that we *can* change its
717                                                 --      binding to be the exported thing!
718
719        not (isExportedId local_id) &&           -- Only if this one is not itself exported,
720                                                 --      since the transformation will nuke it
721    
722        not (local_id `elemVarEnv` ind_env)      -- Only if not already substituted for
723     then
724         True
725
726 {- No longer needed
727         if isEmptySpecInfo (specInfo (idInfo exported_id))      -- Only if no rules
728         then True       -- See note on "Messing up rules"
729         else 
730 #ifdef DEBUG 
731           pprTrace "shortMeOut:" (ppr exported_id)
732 #endif
733                                                 False
734 -}
735     else
736         False
737
738
739 -----------------
740 transferIdInfo :: Id -> Id -> Id
741 -- If we have
742 --      lcl_id = e; exp_id = lcl_id
743 -- and lcl_id has useful IdInfo, we don't want to discard it by going
744 --      gbl_id = e; lcl_id = gbl_id
745 -- Instead, transfer IdInfo from lcl_id to exp_id
746 -- Overwriting, rather than merging, seems to work ok.
747 transferIdInfo exported_id local_id
748   = modifyIdInfo transfer exported_id
749   where
750     local_info = idInfo local_id
751     transfer exp_info = exp_info `setNewStrictnessInfo` newStrictnessInfo local_info
752                                  `setWorkerInfo`        workerInfo local_info
753                                  `setInlinePragInfo`    inlinePragInfo local_info
754                                  `setSpecInfo`          addSpecInfo (specInfo exp_info) new_info
755     new_info = setSpecInfoHead (idName exported_id) 
756                                (specInfo local_info)
757         -- Remember to set the function-name field of the
758         -- rules as we transfer them from one function to another
759 \end{code}