2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Tidying up Core}
7 module TidyPgm( tidyCorePgm, tidyCoreExpr ) where
9 #include "HsVersions.h"
11 import CmdLineOpts ( DynFlags, DynFlag(..), opt_OmitInterfacePragmas )
13 import CoreUnfold ( noUnfolding, mkTopUnfolding )
14 import CoreFVs ( ruleLhsFreeIds, ruleRhsFreeVars, exprSomeFreeVars )
15 import CoreTidy ( tidyExpr, tidyVarOcc, tidyIdRules )
16 import PprCore ( pprIdRules )
17 import CoreLint ( showPass, endPass )
18 import CoreUtils ( exprArity, rhsIsStatic )
21 import Var ( Id, Var )
22 import Id ( idType, idInfo, idName, idCoreRules,
23 isExportedId, mkVanillaGlobal, isLocalId,
24 isImplicitId, idArity, setIdInfo, idCafInfo
26 import IdInfo {- loads of stuff -}
27 import NewDemand ( isBottomingSig, topSig )
28 import BasicTypes ( Arity, isNeverActive )
29 import Name ( getOccName, nameOccName, mkInternalName,
30 localiseName, isExternalName, nameSrcLoc
32 import RnEnv ( lookupOrigNameCache, newExternalName )
33 import NameEnv ( lookupNameEnv, filterNameEnv )
34 import OccName ( TidyOccEnv, initTidyOccEnv, tidyOccName )
35 import Type ( tidyTopType )
36 import Module ( Module )
37 import HscTypes ( PersistentCompilerState( pcs_nc ),
38 NameCache( nsNames, nsUniqs ),
39 TypeEnv, extendTypeEnvList, typeEnvIds,
40 ModGuts(..), ModGuts, TyThing(..)
42 import Maybes ( orElse )
43 import ErrUtils ( showPass, dumpIfSet_core )
44 import UniqFM ( mapUFM )
45 import UniqSupply ( splitUniqSupply, uniqFromSupply )
46 import List ( partition )
47 import Util ( mapAccumL )
48 import Maybe ( isJust )
50 import FastTypes hiding ( fastOr )
54 %************************************************************************
56 \subsection{What goes on}
58 %************************************************************************
64 Step 1: Figure out external Ids
65 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66 First we figure out which Ids are "external" Ids. An
67 "external" Id is one that is visible from outside the compilation
69 a) the user exported ones
70 b) ones mentioned in the unfoldings, workers,
71 or rules of externally-visible ones
72 This exercise takes a sweep of the bindings bottom to top. Actually,
73 in Step 2 we're also going to need to know which Ids should be
74 exported with their unfoldings, so we produce not an IdSet but an
78 Step 2: Tidy the program
79 ~~~~~~~~~~~~~~~~~~~~~~~~
80 Next we traverse the bindings top to bottom. For each *top-level*
83 1. Make it into a GlobalId
85 2. Give it a system-wide Unique.
86 [Even non-exported things need system-wide Uniques because the
87 byte-code generator builds a single Name->BCO symbol table.]
89 We use the NameCache kept in the PersistentCompilerState as the
90 source of such system-wide uniques.
92 For external Ids, use the original-name cache in the NameCache
93 to ensure that the unique assigned is the same as the Id had
94 in any previous compilation run.
96 3. If it's an external Id, make it have a global Name, otherwise
97 make it have a local Name.
98 This is used by the code generator to decide whether
99 to make the label externally visible
101 4. Give external Ids a "tidy" occurrence name. This means
102 we can print them in interface files without confusing
103 "x" (unique 5) with "x" (unique 10).
105 5. Give it its UTTERLY FINAL IdInfo; in ptic,
106 * Its IdDetails becomes VanillaGlobal, reflecting the fact that
107 from now on we regard it as a global, not local, Id
109 * its unfolding, if it should have one
111 * its arity, computed from the number of visible lambdas
113 * its CAF info, computed from what is free in its RHS
116 Finally, substitute these new top-level binders consistently
117 throughout, including in unfoldings. We also tidy binders in
118 RHSs, so that they print nicely in interfaces.
121 tidyCorePgm :: DynFlags
122 -> PersistentCompilerState
124 -> IO (PersistentCompilerState, ModGuts)
126 tidyCorePgm dflags pcs
127 mod_impl@(ModGuts { mg_module = mod,
128 mg_types = env_tc, mg_insts = insts_tc,
129 mg_binds = binds_in, mg_rules = orphans_in })
130 = do { showPass dflags "Tidy Core"
132 ; let ext_ids = findExternalSet binds_in orphans_in
133 ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
134 -- findExternalRules filters ext_rules to avoid binders that
135 -- aren't externally visible; but the externally-visible binders
136 -- are computed (by findExternalSet) assuming that all orphan
137 -- rules are exported. So in fact we may export more than we
138 -- need. (It's a sort of mutual recursion.)
140 -- We also make sure to avoid any exported binders. Consider
141 -- f{-u1-} = 1 -- Local decl
143 -- f{-u2-} = 2 -- Exported decl
145 -- The second exported decl must 'get' the name 'f', so we
146 -- have to put 'f' in the avoids list before we get to the first
147 -- decl. tidyTopId then does a no-op on exported binders.
148 ; let orig_ns = pcs_nc pcs
149 init_tidy_env = (orig_ns, initTidyOccEnv avoids, emptyVarEnv)
150 avoids = [getOccName name | bndr <- typeEnvIds env_tc,
151 let name = idName bndr,
153 -- In computing our "avoids" list, we must include
155 -- all things with global names (assigned once and for
156 -- all by the renamer)
157 -- since their names are "taken".
158 -- The type environment is a convenient source of such things.
160 ; let ((orig_ns', occ_env, subst_env), tidy_binds)
161 = mapAccumL (tidyTopBind mod ext_ids)
162 init_tidy_env binds_in
164 ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
166 ; let pcs' = pcs { pcs_nc = orig_ns' }
168 ; let tidy_type_env = mkFinalTypeEnv env_tc tidy_binds
170 -- Dfuns are local Ids that might have
171 -- changed their unique during tidying. Remember
172 -- to lookup the id in the TypeEnv too, because
173 -- those Ids have had their IdInfo stripped if
175 ; let lookup_dfun_id id =
176 case lookupVarEnv subst_env id of
177 Nothing -> dfun_panic
179 case lookupNameEnv tidy_type_env (idName id) of
183 dfun_panic = pprPanic "lookup_dfun_id" (ppr id)
185 tidy_dfun_ids = map lookup_dfun_id insts_tc
187 ; let tidy_result = mod_impl { mg_types = tidy_type_env,
188 mg_rules = tidy_rules,
189 mg_insts = tidy_dfun_ids,
190 mg_binds = tidy_binds }
192 ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
193 ; dumpIfSet_core dflags Opt_D_dump_simpl
195 (pprIdRules tidy_rules)
197 ; return (pcs', tidy_result)
200 tidyCoreExpr :: CoreExpr -> IO CoreExpr
201 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
205 %************************************************************************
207 \subsection{Write a new interface file}
209 %************************************************************************
212 mkFinalTypeEnv :: TypeEnv -- From typechecker
213 -> [CoreBind] -- Final Ids
216 -- The competed type environment is gotten from
217 -- a) keeping the types and classes
218 -- b) removing all Ids,
219 -- c) adding Ids with correct IdInfo, including unfoldings,
220 -- gotten from the bindings
221 -- From (c) we keep only those Ids with Global names;
222 -- the CoreTidy pass makes sure these are all and only
223 -- the externally-accessible ones
224 -- This truncates the type environment to include only the
225 -- exported Ids and things needed from them, which saves space
227 -- However, we do keep things like constructors, which should not appear
228 -- in interface files, because they are needed by importing modules when
229 -- using the compilation manager
231 mkFinalTypeEnv type_env tidy_binds
232 = extendTypeEnvList (filterNameEnv keep_it type_env) final_ids
234 final_ids = [ AnId (strip_id_info id)
235 | bind <- tidy_binds,
236 id <- bindersOf bind,
237 isExternalName (idName id)]
240 | opt_OmitInterfacePragmas = id `setIdInfo` vanillaIdInfo
242 -- If the interface file has no pragma info then discard all
245 -- This is not so important for *this* module, but it's
246 -- vital for ghc --make:
247 -- subsequent compilations must not see (e.g.) the arity if
248 -- the interface file does not contain arity
249 -- If they do, they'll exploit the arity; then the arity might
250 -- change, but the iface file doesn't change => recompilation
251 -- does not happen => disaster
253 -- This IdInfo will live long-term in the Id => vanillaIdInfo makes
254 -- a conservative assumption about Caf-hood
256 -- We're not worried about occurrences of these Ids in unfoldings,
257 -- because in OmitInterfacePragmas mode we're stripping all the
258 -- unfoldings anyway.
260 -- We keep implicit Ids, because they won't appear
261 -- in the bindings from which final_ids are derived!
262 keep_it (AnId id) = isImplicitId id -- Remove all Ids except implicit ones
263 keep_it other = True -- Keep all TyCons and Classes
267 findExternalRules :: [CoreBind]
268 -> [IdCoreRule] -- Orphan rules
269 -> IdEnv a -- Ids that are exported, so we need their rules
271 -- The complete rules are gotten by combining
272 -- a) the orphan rules
273 -- b) rules embedded in the top-level Ids
274 findExternalRules binds orphan_rules ext_ids
275 | opt_OmitInterfacePragmas = []
277 = filter needed_rule (orphan_rules ++ local_rules)
280 | id <- bindersOfBinds binds,
281 id `elemVarEnv` ext_ids,
282 rule <- idCoreRules id
284 needed_rule (id, rule)
285 = not (isBuiltinRule rule)
286 -- We can't print builtin rules in interface files
287 -- Since they are built in, an importing module
288 -- will have access to them anyway
290 && not (any internal_id (varSetElems (ruleLhsFreeIds rule)))
291 -- Don't export a rule whose LHS mentions an Id that
292 -- is completely internal (i.e. not visible to an
295 internal_id id = isLocalId id && not (id `elemVarEnv` ext_ids)
298 %************************************************************************
300 \subsection{Step 1: finding externals}
302 %************************************************************************
305 findExternalSet :: [CoreBind] -> [IdCoreRule]
306 -> IdEnv Bool -- In domain => external
307 -- Range = True <=> show unfolding
308 -- Step 1 from the notes above
309 findExternalSet binds orphan_rules
310 = foldr find init_needed binds
312 orphan_rule_ids :: IdSet
313 orphan_rule_ids = unionVarSets [ ruleRhsFreeVars rule
314 | (_, rule) <- orphan_rules]
315 init_needed :: IdEnv Bool
316 init_needed = mapUFM (\_ -> False) orphan_rule_ids
317 -- The mapUFM is a bit cheesy. It is a cheap way
318 -- to turn the set of orphan_rule_ids, which we use to initialise
319 -- the sweep, into a mapping saying 'don't expose unfolding'
320 -- (When we come to the binding site we may change our mind, of course.)
322 find (NonRec id rhs) needed
323 | need_id needed id = addExternal (id,rhs) needed
325 find (Rec prs) needed = find_prs prs needed
327 -- For a recursive group we have to look for a fixed point
329 | null needed_prs = needed
330 | otherwise = find_prs other_prs new_needed
332 (needed_prs, other_prs) = partition (need_pr needed) prs
333 new_needed = foldr addExternal needed needed_prs
335 -- The 'needed' set contains the Ids that are needed by earlier
336 -- interface file emissions. If the Id isn't in this set, and isn't
337 -- exported, there's no need to emit anything
338 need_id needed_set id = id `elemVarEnv` needed_set || isExportedId id
339 need_pr needed_set (id,rhs) = need_id needed_set id
341 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
342 -- The Id is needed; extend the needed set
343 -- with it and its dependents (free vars etc)
344 addExternal (id,rhs) needed
345 = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
348 add_occ id needed = extendVarEnv needed id False
349 -- "False" because we don't know we need the Id's unfolding
350 -- We'll override it later when we find the binding site
352 new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
353 | otherwise = worker_ids `unionVarSet`
354 unfold_ids `unionVarSet`
358 dont_inline = isNeverActive (inlinePragInfo idinfo)
359 loop_breaker = isLoopBreaker (occInfo idinfo)
360 bottoming_fn = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
361 spec_ids = rulesRhsFreeVars (specInfo idinfo)
362 worker_info = workerInfo idinfo
364 -- Stuff to do with the Id's unfolding
365 -- The simplifier has put an up-to-date unfolding
366 -- in the IdInfo, but the RHS will do just as well
367 unfolding = unfoldingInfo idinfo
368 rhs_is_small = not (neverUnfold unfolding)
370 -- We leave the unfolding there even if there is a worker
371 -- In GHCI the unfolding is used by importers
372 -- When writing an interface file, we omit the unfolding
373 -- if there is a worker
374 show_unfold = not bottoming_fn && -- Not necessary
377 rhs_is_small -- Small enough
379 unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
380 | otherwise = emptyVarSet
382 worker_ids = case worker_info of
383 HasWorker work_id _ -> unitVarSet work_id
384 otherwise -> emptyVarSet
388 %************************************************************************
390 \subsection{Step 2: top-level tidying}
392 %************************************************************************
396 type TopTidyEnv = (NameCache, TidyOccEnv, VarEnv Var)
398 -- TopTidyEnv: when tidying we need to know
399 -- * ns: The NameCache, containing a unique supply and any pre-ordained Names.
400 -- These may have arisen because the
401 -- renamer read in an interface file mentioning M.$wf, say,
402 -- and assigned it unique r77. If, on this compilation, we've
403 -- invented an Id whose name is $wf (but with a different unique)
404 -- we want to rename it to have unique r77, so that we can do easy
405 -- comparisons with stuff from the interface file
407 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
410 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
415 tidyTopBind :: Module
416 -> IdEnv Bool -- Domain = Ids that should be external
417 -- True <=> their unfolding is external too
418 -> TopTidyEnv -> CoreBind
419 -> (TopTidyEnv, CoreBind)
421 tidyTopBind mod ext_ids top_tidy_env@(_,_,subst1) (NonRec bndr rhs)
422 = ((orig,occ,subst) , NonRec bndr' rhs')
424 ((orig,occ,subst), bndr')
425 = tidyTopBinder mod ext_ids caf_info
426 rec_tidy_env rhs rhs' top_tidy_env bndr
427 rec_tidy_env = (occ,subst)
428 rhs' = tidyExpr rec_tidy_env rhs
429 caf_info = hasCafRefs subst1 (idArity bndr') rhs'
431 tidyTopBind mod ext_ids top_tidy_env@(_,_,subst1) (Rec prs)
432 = (final_env, Rec prs')
434 (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
435 rec_tidy_env = (occ,subst)
437 do_one top_tidy_env (bndr,rhs)
438 = ((orig,occ,subst), (bndr',rhs'))
440 ((orig,occ,subst), bndr')
441 = tidyTopBinder mod ext_ids caf_info
442 rec_tidy_env rhs rhs' top_tidy_env bndr
444 rhs' = tidyExpr rec_tidy_env rhs
446 -- the CafInfo for a recursive group says whether *any* rhs in
447 -- the group may refer indirectly to a CAF (because then, they all do).
449 | or [ mayHaveCafRefs (hasCafRefs subst1 (idArity bndr) rhs)
450 | (bndr,rhs) <- prs ] = MayHaveCafRefs
451 | otherwise = NoCafRefs
453 tidyTopBinder :: Module -> IdEnv Bool -> CafInfo
454 -> TidyEnv -- The TidyEnv is used to tidy the IdInfo
455 -> CoreExpr -- RHS *before* tidying
456 -> CoreExpr -- RHS *after* tidying
457 -- The TidyEnv and the after-tidying RHS are
458 -- both are knot-tied: don't look at them!
459 -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
460 -- NB: tidyTopBinder doesn't affect the unique supply
462 tidyTopBinder mod ext_ids caf_info rec_tidy_env rhs tidy_rhs
463 env@(ns2, occ_env2, subst_env2) id
464 -- This function is the heart of Step 2
465 -- The rec_tidy_env is the one to use for the IdInfo
466 -- It's necessary because when we are dealing with a recursive
467 -- group, a variable late in the group might be mentioned
468 -- in the IdInfo of one early in the group
470 -- The rhs is already tidied
472 = ASSERT(isLocalId id) -- "all Ids defined in this module are local
473 -- until the CoreTidy phase" --GHC comentary
474 ((orig_env', occ_env', subst_env'), id')
476 (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
479 ty' = tidyTopType (idType id)
480 idinfo = tidyTopIdInfo rec_tidy_env is_external
481 (idInfo id) unfold_info arity
484 id' = mkVanillaGlobal name' ty' idinfo
486 subst_env' = extendVarEnv subst_env2 id id'
488 maybe_external = lookupVarEnv ext_ids id
489 is_external = isJust maybe_external
491 -- Expose an unfolding if ext_ids tells us to
492 -- Remember that ext_ids maps an Id to a Bool:
493 -- True to show the unfolding, False to hide it
494 show_unfold = maybe_external `orElse` False
495 unfold_info | show_unfold = mkTopUnfolding tidy_rhs
496 | otherwise = noUnfolding
498 -- Usually the Id will have an accurate arity on it, because
499 -- the simplifier has just run, but not always.
500 -- One case I found was when the last thing the simplifier
501 -- did was to let-bind a non-atomic argument and then float
502 -- it to the top level. So it seems more robust just to
504 arity = exprArity rhs
507 -- tidyTopIdInfo creates the final IdInfo for top-level
508 -- binders. There are two delicate pieces:
510 -- * Arity. After CoreTidy, this arity must not change any more.
511 -- Indeed, CorePrep must eta expand where necessary to make
512 -- the manifest arity equal to the claimed arity.
514 -- * CAF info. This must also remain valid through to code generation.
515 -- We add the info here so that it propagates to all
516 -- occurrences of the binders in RHSs, and hence to occurrences in
517 -- unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
518 -- CoreToStg makes use of this when constructing SRTs.
520 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
521 | not is_external -- For internal Ids (not externally visible)
522 = vanillaIdInfo -- we only need enough info for code generation
523 -- Arity and strictness info are enough;
524 -- c.f. CoreTidy.tidyLetBndr
525 `setCafInfo` caf_info
527 `setAllStrictnessInfo` newStrictnessInfo idinfo
529 | otherwise -- Externally-visible Ids get the whole lot
531 `setCafInfo` caf_info
533 `setAllStrictnessInfo` newStrictnessInfo idinfo
534 `setInlinePragInfo` inlinePragInfo idinfo
535 `setUnfoldingInfo` unfold_info
536 `setWorkerInfo` tidyWorker tidy_env (workerInfo idinfo)
537 -- NB: we throw away the Rules
538 -- They have already been extracted by findExternalRules
541 -- This is where we set names to local/global based on whether they really are
542 -- externally visible (see comment at the top of this module). If the name
543 -- was previously local, we have to give it a unique occurrence name if
544 -- we intend to externalise it.
545 tidyTopName mod ns occ_env external name
546 | global && internal = (ns, occ_env, localiseName name)
548 | global && external = (ns, occ_env, name)
549 -- Global names are assumed to have been allocated by the renamer,
550 -- so they already have the "right" unique
551 -- And it's a system-wide unique too
553 | local && internal = (ns_w_local, occ_env', new_local_name)
554 -- Even local, internal names must get a unique occurrence, because
555 -- if we do -split-objs we externalise the name later, in the code generator
557 -- Similarly, we must make sure it has a system-wide Unique, because
558 -- the byte-code generator builds a system-wide Name->BCO symbol table
560 | local && external = case lookupOrigNameCache ns_names mod occ' of
561 Just orig -> (ns, occ_env', orig)
562 Nothing -> (ns_w_global, occ_env', new_external_name)
563 -- If we want to externalise a currently-local name, check
564 -- whether we have already assigned a unique for it.
565 -- If so, use it; if not, extend the table (ns_w_global).
566 -- This is needed when *re*-compiling a module in GHCi; we want to
567 -- use the same name for externally-visible things as we did before.
570 global = isExternalName name
572 internal = not external
573 loc = nameSrcLoc name
575 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
577 ns_names = nsNames ns
578 (us1, us2) = splitUniqSupply (nsUniqs ns)
579 uniq = uniqFromSupply us1
580 new_local_name = mkInternalName uniq occ' loc
581 ns_w_local = ns { nsUniqs = us2 }
583 (ns_w_global, new_external_name) = newExternalName ns mod occ' loc
586 ------------ Worker --------------
587 tidyWorker tidy_env (HasWorker work_id wrap_arity)
588 = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
589 tidyWorker tidy_env other
593 %************************************************************************
595 \subsection{Figuring out CafInfo for an expression}
597 %************************************************************************
599 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
600 We mark such things as `MayHaveCafRefs' because this information is
601 used to decide whether a particular closure needs to be referenced
604 There are two reasons for setting MayHaveCafRefs:
605 a) The RHS is a CAF: a top-level updatable thunk.
606 b) The RHS refers to something that MayHaveCafRefs
608 Possible improvement: In an effort to keep the number of CAFs (and
609 hence the size of the SRTs) down, we could also look at the expression and
610 decide whether it requires a small bounded amount of heap, so we can ignore
611 it as a CAF. In these cases however, we would need to use an additional
612 CAF list to keep track of non-collectable CAFs.
615 hasCafRefs :: VarEnv Var -> Arity -> CoreExpr -> CafInfo
616 hasCafRefs p arity expr
617 | is_caf || mentions_cafs = MayHaveCafRefs
618 | otherwise = NoCafRefs
620 mentions_cafs = isFastTrue (cafRefs p expr)
621 is_caf = not (arity > 0 || rhsIsStatic expr)
622 -- NB. we pass in the arity of the expression, which is expected
623 -- to be calculated by exprArity. This is because exprArity
624 -- knows how much eta expansion is going to be done by
625 -- CorePrep later on, and we don't want to duplicate that
626 -- knowledge in rhsIsStatic below.
629 -- imported Ids first:
630 | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
631 -- now Ids local to this module:
633 case lookupVarEnv p id of
634 Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
635 Nothing -> fastBool False
637 cafRefs p (Lit l) = fastBool False
638 cafRefs p (App f a) = fastOr (cafRefs p f) (cafRefs p) a
639 cafRefs p (Lam x e) = cafRefs p e
640 cafRefs p (Let b e) = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
641 cafRefs p (Case e bndr alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
642 cafRefs p (Note n e) = cafRefs p e
643 cafRefs p (Type t) = fastBool False
645 cafRefss p [] = fastBool False
646 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
648 -- hack for lazy-or over FastBool.
649 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))