2a305073f7e06fa80e27ef86dcba97def6105e60
[ghc-hetmet.git] / ghc / 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 module SimplCore ( core2core ) where
8
9 #include "HsVersions.h"
10
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,
19                           opt_UsageSPOn,
20                         )
21 import CoreLint         ( beginPass, endPass )
22 import CoreTidy         ( tidyCorePgm )
23 import CoreSyn
24 import Rules            ( RuleBase, ProtoCoreRule(..), pprProtoCoreRule, prepareRuleBase, orphanRule )
25 import CoreUnfold
26 import PprCore          ( pprCoreBindings )
27 import OccurAnal        ( occurAnalyseBinds )
28 import CoreUtils        ( exprIsTrivial, coreExprType )
29 import Simplify         ( simplTopBinds, simplExpr )
30 import SimplUtils       ( etaCoreExpr, findDefault, simplBinders )
31 import SimplMonad
32 import Const            ( Con(..), Literal(..), literalType, mkMachInt )
33 import ErrUtils         ( dumpIfSet )
34 import FloatIn          ( floatInwards )
35 import FloatOut         ( floatOutwards )
36 import Id               ( Id, mkSysLocal, mkVanillaId, isBottomingId,
37                           idType, setIdType, idName, idInfo, setIdNoDiscard
38                         )
39 import IdInfo           ( InlinePragInfo(..), specInfo, setSpecInfo,
40                           inlinePragInfo, setInlinePragInfo,
41                           setUnfoldingInfo, setDemandInfo
42                         )
43 import Demand           ( wwLazy )
44 import VarEnv
45 import VarSet
46 import Module           ( Module )
47 import Name             ( mkLocalName, tidyOccName, tidyTopName, 
48                           NamedThing(..), OccName
49                         )
50 import TyCon            ( TyCon, isDataTyCon )
51 import PrimOp           ( PrimOp(..) )
52 import PrelInfo         ( unpackCStringId, unpackCString2Id, addr2IntegerId )
53 import Type             ( Type, splitAlgTyConApp_maybe, 
54                           isUnLiftedType,
55                           tidyType, tidyTypes, tidyTopType, tidyTyVar, tidyTyVars,
56                           Type
57                         )
58 import TysWiredIn       ( smallIntegerDataCon, isIntegerTy )
59 import LiberateCase     ( liberateCase )
60 import SAT              ( doStaticArgs )
61 import Specialise       ( specProgram)
62 import UsageSPInf       ( doUsageSPInf )
63 import StrictAnal       ( saBinds )
64 import WorkWrap         ( wwTopBinds )
65 import CprAnalyse       ( cprAnalyse )
66
67 import Unique           ( Unique, Uniquable(..),
68                           ratioTyConKey
69                         )
70 import UniqSupply       ( UniqSupply, mkSplitUniqSupply, splitUniqSupply, uniqFromSupply )
71 import Constants        ( tARGET_MIN_INT, tARGET_MAX_INT )
72 import Util             ( mapAccumL )
73 import SrcLoc           ( noSrcLoc )
74 import Bag
75 import Maybes
76 import IO               ( hPutStr, stderr )
77 import Outputable
78
79 import Ratio            ( numerator, denominator )
80 \end{code}
81
82 %************************************************************************
83 %*                                                                      *
84 \subsection{The driver for the simplifier}
85 %*                                                                      *
86 %************************************************************************
87
88 \begin{code}
89 core2core :: [CoreToDo]         -- Spec of what core-to-core passes to do
90           -> [CoreBind]         -- Binds in
91           -> [ProtoCoreRule]    -- Rules
92           -> IO ([CoreBind], [ProtoCoreRule])
93
94 core2core core_todos binds rules
95   = do
96         us <-  mkSplitUniqSupply 's'
97         let (cp_us, us1)   = splitUniqSupply us
98             (ru_us, ps_us) = splitUniqSupply us1
99
100         better_rules <- simplRules ru_us rules binds
101
102         let (binds1, rule_base) = prepareRuleBase binds better_rules
103
104         -- Do the main business
105         (stats, processed_binds) <- doCorePasses zeroSimplCount cp_us binds1 
106                                                  rule_base core_todos
107
108         dumpIfSet opt_D_dump_simpl_stats
109                   "Grand total simplifier statistics"
110                   (pprSimplCount stats)
111
112         -- Do the post-simplification business
113         post_simpl_binds <- doPostSimplification ps_us processed_binds
114
115         -- Return results
116         return (post_simpl_binds, filter orphanRule better_rules)
117    
118
119 doCorePasses stats us binds irs []
120   = return (stats, binds)
121
122 doCorePasses stats us binds irs (to_do : to_dos) 
123   = do
124         let (us1, us2) =  splitUniqSupply us
125         (stats1, binds1) <- doCorePass us1 binds irs to_do
126         doCorePasses (stats `plusSimplCount` stats1) us2 binds1 irs to_dos
127
128 doCorePass us binds rb (CoreDoSimplify sw_chkr) = _scc_ "Simplify"      simplifyPgm rb sw_chkr us binds
129 doCorePass us binds rb CoreLiberateCase         = _scc_ "LiberateCase"  noStats (liberateCase binds)
130 doCorePass us binds rb CoreDoFloatInwards       = _scc_ "FloatInwards"  noStats (floatInwards binds)
131 doCorePass us binds rb CoreDoFullLaziness       = _scc_ "FloatOutwards" noStats (floatOutwards us binds)
132 doCorePass us binds rb CoreDoStaticArgs         = _scc_ "StaticArgs"    noStats (doStaticArgs us binds)
133 doCorePass us binds rb CoreDoStrictness         = _scc_ "Stranal"       noStats (saBinds binds)
134 doCorePass us binds rb CoreDoWorkerWrapper      = _scc_ "WorkWrap"      noStats (wwTopBinds us binds)
135 doCorePass us binds rb CoreDoSpecialising       = _scc_ "Specialise"    noStats (specProgram us binds)
136 doCorePass us binds rb CoreDoCPResult           = _scc_ "CPResult"      noStats (cprAnalyse binds)
137 doCorePass us binds rb CoreDoPrintCore          = _scc_ "PrintCore"     noStats (printCore binds)
138 doCorePass us binds rb CoreDoUSPInf
139   = _scc_ "CoreUsageSPInf" 
140     if opt_UsageSPOn then
141       noStats (doUsageSPInf us binds)
142     else
143       trace "WARNING: ignoring requested -fusagesp pass; requires -fusagesp-on" $
144       noStats (return binds)
145
146 printCore binds = do dumpIfSet True "Print Core"
147                                (pprCoreBindings binds)
148                      return binds
149
150 noStats thing = do { result <- thing; return (zeroSimplCount, result) }
151 \end{code}
152
153
154 %************************************************************************
155 %*                                                                      *
156 \subsection{Dealing with rules}
157 %*                                                                      *
158 %************************************************************************
159
160 We must do some gentle simplifiation on the template (but not the RHS)
161 of each rule.  The case that forced me to add this was the fold/build rule,
162 which without simplification looked like:
163         fold k z (build (/\a. g a))  ==>  ...
164 This doesn't match unless you do eta reduction on the build argument.
165
166 \begin{code}
167 simplRules :: UniqSupply -> [ProtoCoreRule] -> [CoreBind] -> IO [ProtoCoreRule]
168 simplRules us rules binds
169   = do  let (better_rules,_) = initSmpl sw_chkr us bind_vars black_list_all (mapSmpl simplRule rules)
170         
171         dumpIfSet opt_D_dump_rules
172                   "Transformation rules"
173                   (vcat (map pprProtoCoreRule better_rules))
174
175         return better_rules
176   where
177     black_list_all v = True             -- This stops all inlining
178     sw_chkr any = SwBool False          -- A bit bogus
179
180         -- Boringly, we need to gather the in-scope set.
181         -- Typically this thunk won't even be force, but the test in
182         -- simpVar fails if it isn't right, and it might conceivably matter
183     bind_vars = foldr (unionVarSet . mkVarSet . bindersOf) emptyVarSet binds
184
185
186 simplRule rule@(ProtoCoreRule is_local id (Rule name bndrs args rhs))
187   | not is_local
188   = returnSmpl rule     -- No need to fiddle with imported rules
189   | otherwise
190   = simplBinders bndrs                  $ \ bndrs' -> 
191     mapSmpl simplExpr args              `thenSmpl` \ args' ->
192     simplExpr rhs                       `thenSmpl` \ rhs' ->
193     returnSmpl (ProtoCoreRule is_local id (Rule name bndrs' args' rhs'))
194 \end{code}
195
196 %************************************************************************
197 %*                                                                      *
198 \subsection{The driver for the simplifier}
199 %*                                                                      *
200 %************************************************************************
201
202 \begin{code}
203 simplifyPgm :: RuleBase
204             -> (SimplifierSwitch -> SwitchResult)
205             -> UniqSupply
206             -> [CoreBind]                               -- Input
207             -> IO (SimplCount, [CoreBind])              -- New bindings
208
209 simplifyPgm (imported_rule_ids, rule_lhs_fvs) 
210             sw_chkr us binds
211   = do {
212         beginPass "Simplify";
213
214         -- Glom all binds together in one Rec, in case any
215         -- transformations have introduced any new dependencies
216         let { recd_binds = [Rec (flattenBinds binds)] };
217
218         (termination_msg, it_count, counts_out, binds') <- iteration us 1 zeroSimplCount recd_binds;
219
220         dumpIfSet (opt_D_verbose_core2core && opt_D_dump_simpl_stats)
221                   "Simplifier statistics"
222                   (vcat [text termination_msg <+> text "after" <+> ppr it_count <+> text "iterations",
223                          text "",
224                          pprSimplCount counts_out]);
225
226         endPass "Simplify" 
227                 (opt_D_verbose_core2core && not opt_D_dump_simpl_iterations)
228                 binds' ;
229
230         return (counts_out, binds')
231     }
232   where
233     max_iterations = getSimplIntSwitch sw_chkr MaxSimplifierIterations
234     black_list_fn  = blackListed rule_lhs_fvs (intSwitchSet sw_chkr SimplInlinePhase)
235
236     core_iter_dump binds | opt_D_verbose_core2core = pprCoreBindings binds
237                          | otherwise               = empty
238
239     iteration us iteration_no counts binds
240       = do {
241                 -- Occurrence analysis
242            let { tagged_binds = _scc_ "OccAnal" occurAnalyseBinds binds } ;
243
244            dumpIfSet opt_D_dump_occur_anal "Occurrence analysis"
245                      (pprCoreBindings tagged_binds);
246
247                 -- Simplify
248            let { (binds', counts') = initSmpl sw_chkr us1 imported_rule_ids 
249                                               black_list_fn 
250                                               (simplTopBinds tagged_binds);
251                  all_counts        = counts `plusSimplCount` counts'
252                } ;
253
254                 -- Stop if nothing happened; don't dump output
255            if isZeroSimplCount counts' then
256                 return ("Simplifier reached fixed point", iteration_no, all_counts, binds')
257            else do {
258
259                 -- Dump the result of this iteration
260            dumpIfSet opt_D_dump_simpl_iterations
261                      ("Simplifier iteration " ++ show iteration_no 
262                       ++ " out of " ++ show max_iterations)
263                      (pprSimplCount counts') ;
264
265            if opt_D_dump_simpl_iterations then
266                 endPass ("Simplifier iteration " ++ show iteration_no ++ " result")
267                         opt_D_verbose_core2core
268                         binds'
269            else
270                 return [] ;
271
272                 -- Stop if we've run out of iterations
273            if iteration_no == max_iterations then
274                 do {
275                     if  max_iterations > 2 then
276                             hPutStr stderr ("NOTE: Simplifier still going after " ++ 
277                                     show max_iterations ++ 
278                                     " iterations; bailing out.\n")
279                     else return ();
280
281                     return ("Simplifier baled out", iteration_no, all_counts, binds')
282                 }
283
284                 -- Else loop
285            else iteration us2 (iteration_no + 1) all_counts binds'
286         }  }
287       where
288           (us1, us2) = splitUniqSupply us
289 \end{code}
290
291
292 %************************************************************************
293 %*                                                                      *
294 \subsection{PostSimplification}
295 %*                                                                      *
296 %************************************************************************
297
298 Several tasks are performed by the post-simplification pass
299
300 1.  Make the representation of NoRep literals explicit, and
301     float their bindings to the top level.  We only do the floating
302     part for NoRep lits inside a lambda (else no gain).  We need to
303     take care with      let x = "foo" in e
304     that we don't end up with a silly binding
305                         let x = y in e
306     with a floated "foo".  What a bore.
307     
308 2.  *Mangle* cases involving par# in the discriminant.  The unfolding
309     for par in PrelConc.lhs include case expressions with integer
310     results solely to fool the strictness analyzer, the simplifier,
311     and anyone else who might want to fool with the evaluation order.
312     At this point in the compiler our evaluation order is safe.
313     Therefore, we convert expressions of the form:
314
315         case par# e of
316           0# -> rhs
317           _  -> parError#
318     ==>
319         case par# e of
320           _ -> rhs
321
322     fork# isn't handled like this - it's an explicit IO operation now.
323     The reason is that fork# returns a ThreadId#, which gets in the
324     way of the above scheme.  And anyway, IO is the only guaranteed
325     way to enforce ordering  --SDM.
326
327 4. Do eta reduction for lambda abstractions appearing in:
328         - the RHS of case alternatives
329         - the body of a let
330
331    These will otherwise turn into local bindings during Core->STG;
332    better to nuke them if possible.  (In general the simplifier does
333    eta expansion not eta reduction, up to this point.  It does eta
334    on the RHSs of bindings but not the RHSs of case alternatives and
335    let bodies)
336
337
338 ------------------- NOT DONE ANY MORE ------------------------
339 [March 98] Indirections are now elimianted by the occurrence analyser
340 1.  Eliminate indirections.  The point here is to transform
341         x_local = E
342         x_exported = x_local
343     ==>
344         x_exported = E
345
346 [Dec 98] [Not now done because there is no penalty in the code
347           generator for using the former form]
348 2.  Convert
349         case x of {...; x' -> ...x'...}
350     ==>
351         case x of {...; _  -> ...x... }
352     See notes in SimplCase.lhs, near simplDefault for the reasoning here.
353 --------------------------------------------------------------
354
355 Special case
356 ~~~~~~~~~~~~
357
358 NOT ENABLED AT THE MOMENT (because the floated Ids are global-ish
359 things, and we need local Ids for non-floated stuff):
360
361   Don't float stuff out of a binder that's marked as a bottoming Id.
362   Reason: it doesn't do any good, and creates more CAFs that increase
363   the size of SRTs.
364
365 eg.
366
367         f = error "string"
368
369 is translated to
370
371         f' = unpackCString# "string"
372         f = error f'
373
374 hence f' and f become CAFs.  Instead, the special case for
375 tidyTopBinding below makes sure this comes out as
376
377         f = let f' = unpackCString# "string" in error f'
378
379 and we can safely ignore f as a CAF, since it can only ever be entered once.
380
381
382
383 \begin{code}
384 doPostSimplification :: UniqSupply -> [CoreBind] -> IO [CoreBind]
385 doPostSimplification us binds_in
386   = do
387         beginPass "Post-simplification pass"
388         let binds_out = initPM us (postSimplTopBinds binds_in)
389         endPass "Post-simplification pass" opt_D_verbose_core2core binds_out
390
391 postSimplTopBinds :: [CoreBind] -> PostM [CoreBind]
392 postSimplTopBinds binds
393   = mapPM postSimplTopBind binds        `thenPM` \ binds' ->
394     returnPM (bagToList (unionManyBags binds'))
395
396 postSimplTopBind :: CoreBind -> PostM (Bag CoreBind)
397 postSimplTopBind (NonRec bndr rhs)
398   | isBottomingId bndr          -- Don't lift out floats for bottoming Ids
399                                 -- See notes above
400   = getFloatsPM (postSimplExpr rhs)     `thenPM` \ (rhs', floats) ->
401     returnPM (unitBag (NonRec bndr (foldrBag Let rhs' floats)))
402
403 postSimplTopBind bind
404   = getFloatsPM (postSimplBind bind)    `thenPM` \ (bind', floats) ->
405     returnPM (floats `snocBag` bind')
406
407 postSimplBind (NonRec bndr rhs)
408   = postSimplExpr rhs           `thenPM` \ rhs' ->
409     returnPM (NonRec bndr rhs')
410
411 postSimplBind (Rec pairs)
412   = mapPM postSimplExpr rhss    `thenPM` \ rhss' ->
413     returnPM (Rec (bndrs `zip` rhss'))
414   where
415     (bndrs, rhss) = unzip pairs
416 \end{code}
417
418
419 Expressions
420 ~~~~~~~~~~~
421 \begin{code}
422 postSimplExpr (Var v)   = returnPM (Var v)
423 postSimplExpr (Type ty) = returnPM (Type ty)
424
425 postSimplExpr (App fun arg)
426   = postSimplExpr fun   `thenPM` \ fun' ->
427     postSimplExpr arg   `thenPM` \ arg' ->
428     returnPM (App fun' arg')
429
430 postSimplExpr (Con (Literal lit) args)
431   = ASSERT( null args )
432     litToRep lit        `thenPM` \ (lit_ty, lit_expr) ->
433     getInsideLambda     `thenPM` \ in_lam ->
434     if in_lam && not (exprIsTrivial lit_expr) then
435         -- It must have been a no-rep literal with a
436         -- non-trivial representation; and we're inside a lambda;
437         -- so float it to the top
438         addTopFloat lit_ty lit_expr     `thenPM` \ v ->
439         returnPM (Var v)
440     else
441         returnPM lit_expr
442
443 postSimplExpr (Con con args)
444   = mapPM postSimplExpr args    `thenPM` \ args' ->
445     returnPM (Con con args')
446
447 postSimplExpr (Lam bndr body)
448   = insideLambda bndr           $
449     postSimplExpr body          `thenPM` \ body' ->
450     returnPM (Lam bndr body')
451
452 postSimplExpr (Let bind body)
453   = postSimplBind bind          `thenPM` \ bind' ->
454     postSimplExprEta body       `thenPM` \ body' ->
455     returnPM (Let bind' body')
456
457 postSimplExpr (Note note body)
458   = postSimplExprEta body       `thenPM` \ body' ->
459     returnPM (Note note body')
460
461 -- par#: see notes above.
462 postSimplExpr (Case scrut@(Con (PrimOp op) args) bndr alts)
463   | funnyParallelOp op && maybeToBool maybe_default
464   = postSimplExpr scrut                 `thenPM` \ scrut' ->
465     postSimplExprEta default_rhs        `thenPM` \ rhs' ->
466     returnPM (Case scrut' bndr [(DEFAULT,[],rhs')])
467   where
468     (other_alts, maybe_default)  = findDefault alts
469     Just default_rhs             = maybe_default
470
471 postSimplExpr (Case scrut case_bndr alts)
472   = postSimplExpr scrut                 `thenPM` \ scrut' ->
473     mapPM ps_alt alts                   `thenPM` \ alts' ->
474     returnPM (Case scrut' case_bndr alts')
475   where
476     ps_alt (con,bndrs,rhs) = postSimplExprEta rhs       `thenPM` \ rhs' ->
477                              returnPM (con, bndrs, rhs')
478
479 postSimplExprEta e = postSimplExpr e    `thenPM` \ e' ->
480                      returnPM (etaCoreExpr e')
481 \end{code}
482
483 \begin{code}
484 funnyParallelOp ParOp  = True
485 funnyParallelOp _      = False
486 \end{code}  
487
488
489 %************************************************************************
490 %*                                                                      *
491 \subsection[coreToStg-lits]{Converting literals}
492 %*                                                                      *
493 %************************************************************************
494
495 Literals: the NoRep kind need to be de-no-rep'd.
496 We always replace them with a simple variable, and float a suitable
497 binding out to the top level.
498
499 \begin{code}
500 litToRep :: Literal -> PostM (Type, CoreExpr)
501
502 litToRep (NoRepStr s ty)
503   = returnPM (ty, rhs)
504   where
505     rhs = if (any is_NUL (_UNPK_ s))
506
507           then   -- Must cater for NULs in literal string
508                 mkApps (Var unpackCString2Id)
509                        [mkLit (MachStr s),
510                         mkLit (mkMachInt (toInteger (_LENGTH_ s)))]
511
512           else  -- No NULs in the string
513                 App (Var unpackCStringId) (mkLit (MachStr s))
514
515     is_NUL c = c == '\0'
516 \end{code}
517
518 If an Integer is small enough (Haskell implementations must support
519 Ints in the range $[-2^29+1, 2^29-1]$), wrap it up in @int2Integer@;
520 otherwise, wrap with @addr2Integer@.
521
522 \begin{code}
523 litToRep (NoRepInteger i integer_ty)
524   = returnPM (integer_ty, rhs)
525   where
526     rhs | i > tARGET_MIN_INT &&         -- Small enough, so start from an Int
527           i < tARGET_MAX_INT
528         = Con (DataCon smallIntegerDataCon) [Con (Literal (mkMachInt i)) []]
529   
530         | otherwise                     -- Big, so start from a string
531         = App (Var addr2IntegerId) (Con (Literal (MachStr (_PK_ (show i)))) [])
532
533
534 litToRep (NoRepRational r rational_ty)
535   = postSimplExpr (mkLit (NoRepInteger (numerator   r) integer_ty))     `thenPM` \ num_arg ->
536     postSimplExpr (mkLit (NoRepInteger (denominator r) integer_ty))     `thenPM` \ denom_arg ->
537     returnPM (rational_ty, mkConApp ratio_data_con [Type integer_ty, num_arg, denom_arg])
538   where
539     (ratio_data_con, integer_ty)
540       = case (splitAlgTyConApp_maybe rational_ty) of
541           Just (tycon, [i_ty], [con])
542             -> ASSERT(isIntegerTy i_ty && getUnique tycon == ratioTyConKey)
543                (con, i_ty)
544
545           _ -> (panic "ratio_data_con", panic "integer_ty")
546
547 litToRep other_lit = returnPM (literalType other_lit, mkLit other_lit)
548 \end{code}
549
550
551 %************************************************************************
552 %*                                                                      *
553 \subsection{The monad}
554 %*                                                                      *
555 %************************************************************************
556
557 \begin{code}
558 type PostM a =  Bool                            -- True <=> inside a *value* lambda
559              -> (UniqSupply, Bag CoreBind)      -- Unique supply and Floats in 
560              -> (a, (UniqSupply, Bag CoreBind))
561
562 initPM :: UniqSupply -> PostM a -> a
563 initPM us m
564   = case m False {- not inside lambda -} (us, emptyBag) of 
565         (result, _) -> result
566
567 returnPM v in_lam usf = (v, usf)
568 thenPM m k in_lam usf = case m in_lam usf of
569                                   (r, usf') -> k r in_lam usf'
570
571 mapPM f []     = returnPM []
572 mapPM f (x:xs) = f x            `thenPM` \ r ->
573                  mapPM f xs     `thenPM` \ rs ->
574                  returnPM (r:rs)
575
576 insideLambda :: CoreBndr -> PostM a -> PostM a
577 insideLambda bndr m in_lam usf | isId bndr = m True   usf
578                                | otherwise = m in_lam usf
579
580 getInsideLambda :: PostM Bool
581 getInsideLambda in_lam usf = (in_lam, usf)
582
583 getFloatsPM :: PostM a -> PostM (a, Bag CoreBind)
584 getFloatsPM m in_lam (us, floats)
585   = let
586         (a, (us', floats')) = m in_lam (us, emptyBag)
587     in
588     ((a, floats'), (us', floats))
589
590 addTopFloat :: Type -> CoreExpr -> PostM Id
591 addTopFloat lit_ty lit_rhs in_lam (us, floats)
592   = let
593         (us1, us2) = splitUniqSupply us
594         uniq       = uniqFromSupply us1
595         lit_id     = mkSysLocal SLIT("lf") uniq lit_ty
596     in
597     (lit_id, (us2, floats `snocBag` NonRec lit_id lit_rhs))
598 \end{code}
599
600