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, okToUnfoldInHiFile )
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
378 okToUnfoldInHiFile rhs -- No casms etc
380 unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
381 | otherwise = emptyVarSet
383 worker_ids = case worker_info of
384 HasWorker work_id _ -> unitVarSet work_id
385 otherwise -> emptyVarSet
389 %************************************************************************
391 \subsection{Step 2: top-level tidying}
393 %************************************************************************
397 type TopTidyEnv = (NameCache, TidyOccEnv, VarEnv Var)
399 -- TopTidyEnv: when tidying we need to know
400 -- * ns: The NameCache, containing a unique supply and any pre-ordained Names.
401 -- These may have arisen because the
402 -- renamer read in an interface file mentioning M.$wf, say,
403 -- and assigned it unique r77. If, on this compilation, we've
404 -- invented an Id whose name is $wf (but with a different unique)
405 -- we want to rename it to have unique r77, so that we can do easy
406 -- comparisons with stuff from the interface file
408 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
411 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
416 tidyTopBind :: Module
417 -> IdEnv Bool -- Domain = Ids that should be external
418 -- True <=> their unfolding is external too
419 -> TopTidyEnv -> CoreBind
420 -> (TopTidyEnv, CoreBind)
422 tidyTopBind mod ext_ids top_tidy_env@(_,_,subst1) (NonRec bndr rhs)
423 = ((orig,occ,subst) , NonRec bndr' rhs')
425 ((orig,occ,subst), bndr')
426 = tidyTopBinder mod ext_ids caf_info
427 rec_tidy_env rhs rhs' top_tidy_env bndr
428 rec_tidy_env = (occ,subst)
429 rhs' = tidyExpr rec_tidy_env rhs
430 caf_info = hasCafRefs subst1 (idArity bndr') rhs'
432 tidyTopBind mod ext_ids top_tidy_env@(_,_,subst1) (Rec prs)
433 = (final_env, Rec prs')
435 (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
436 rec_tidy_env = (occ,subst)
438 do_one top_tidy_env (bndr,rhs)
439 = ((orig,occ,subst), (bndr',rhs'))
441 ((orig,occ,subst), bndr')
442 = tidyTopBinder mod ext_ids caf_info
443 rec_tidy_env rhs rhs' top_tidy_env bndr
445 rhs' = tidyExpr rec_tidy_env rhs
447 -- the CafInfo for a recursive group says whether *any* rhs in
448 -- the group may refer indirectly to a CAF (because then, they all do).
450 | or [ mayHaveCafRefs (hasCafRefs subst1 (idArity bndr) rhs)
451 | (bndr,rhs) <- prs ] = MayHaveCafRefs
452 | otherwise = NoCafRefs
454 tidyTopBinder :: Module -> IdEnv Bool -> CafInfo
455 -> TidyEnv -- The TidyEnv is used to tidy the IdInfo
456 -> CoreExpr -- RHS *before* tidying
457 -> CoreExpr -- RHS *after* tidying
458 -- The TidyEnv and the after-tidying RHS are
459 -- both are knot-tied: don't look at them!
460 -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
461 -- NB: tidyTopBinder doesn't affect the unique supply
463 tidyTopBinder mod ext_ids caf_info rec_tidy_env rhs tidy_rhs
464 env@(ns2, occ_env2, subst_env2) id
465 -- This function is the heart of Step 2
466 -- The rec_tidy_env is the one to use for the IdInfo
467 -- It's necessary because when we are dealing with a recursive
468 -- group, a variable late in the group might be mentioned
469 -- in the IdInfo of one early in the group
471 -- The rhs is already tidied
473 = ASSERT(isLocalId id) -- "all Ids defined in this module are local
474 -- until the CoreTidy phase" --GHC comentary
475 ((orig_env', occ_env', subst_env'), id')
477 (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
480 ty' = tidyTopType (idType id)
481 idinfo = tidyTopIdInfo rec_tidy_env is_external
482 (idInfo id) unfold_info arity
485 id' = mkVanillaGlobal name' ty' idinfo
487 subst_env' = extendVarEnv subst_env2 id id'
489 maybe_external = lookupVarEnv ext_ids id
490 is_external = isJust maybe_external
492 -- Expose an unfolding if ext_ids tells us to
493 -- Remember that ext_ids maps an Id to a Bool:
494 -- True to show the unfolding, False to hide it
495 show_unfold = maybe_external `orElse` False
496 unfold_info | show_unfold = mkTopUnfolding tidy_rhs
497 | otherwise = noUnfolding
499 -- Usually the Id will have an accurate arity on it, because
500 -- the simplifier has just run, but not always.
501 -- One case I found was when the last thing the simplifier
502 -- did was to let-bind a non-atomic argument and then float
503 -- it to the top level. So it seems more robust just to
505 arity = exprArity rhs
508 -- tidyTopIdInfo creates the final IdInfo for top-level
509 -- binders. There are two delicate pieces:
511 -- * Arity. After CoreTidy, this arity must not change any more.
512 -- Indeed, CorePrep must eta expand where necessary to make
513 -- the manifest arity equal to the claimed arity.
515 -- * CAF info. This must also remain valid through to code generation.
516 -- We add the info here so that it propagates to all
517 -- occurrences of the binders in RHSs, and hence to occurrences in
518 -- unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
519 -- CoreToStg makes use of this when constructing SRTs.
521 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
522 | not is_external -- For internal Ids (not externally visible)
523 = vanillaIdInfo -- we only need enough info for code generation
524 -- Arity and strictness info are enough;
525 -- c.f. CoreTidy.tidyLetBndr
526 `setCafInfo` caf_info
528 `setAllStrictnessInfo` newStrictnessInfo idinfo
530 | otherwise -- Externally-visible Ids get the whole lot
532 `setCafInfo` caf_info
534 `setAllStrictnessInfo` newStrictnessInfo idinfo
535 `setInlinePragInfo` inlinePragInfo idinfo
536 `setUnfoldingInfo` unfold_info
537 `setWorkerInfo` tidyWorker tidy_env (workerInfo idinfo)
538 -- NB: we throw away the Rules
539 -- They have already been extracted by findExternalRules
542 -- This is where we set names to local/global based on whether they really are
543 -- externally visible (see comment at the top of this module). If the name
544 -- was previously local, we have to give it a unique occurrence name if
545 -- we intend to externalise it.
546 tidyTopName mod ns occ_env external name
547 | global && internal = (ns, occ_env, localiseName name)
549 | global && external = (ns, occ_env, name)
550 -- Global names are assumed to have been allocated by the renamer,
551 -- so they already have the "right" unique
552 -- And it's a system-wide unique too
554 | local && internal = (ns_w_local, occ_env', new_local_name)
555 -- Even local, internal names must get a unique occurrence, because
556 -- if we do -split-objs we externalise the name later, in the code generator
558 -- Similarly, we must make sure it has a system-wide Unique, because
559 -- the byte-code generator builds a system-wide Name->BCO symbol table
561 | local && external = case lookupOrigNameCache ns_names mod occ' of
562 Just orig -> (ns, occ_env', orig)
563 Nothing -> (ns_w_global, occ_env', new_external_name)
564 -- If we want to externalise a currently-local name, check
565 -- whether we have already assigned a unique for it.
566 -- If so, use it; if not, extend the table (ns_w_global).
567 -- This is needed when *re*-compiling a module in GHCi; we want to
568 -- use the same name for externally-visible things as we did before.
571 global = isExternalName name
573 internal = not external
574 loc = nameSrcLoc name
576 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
578 ns_names = nsNames ns
579 (us1, us2) = splitUniqSupply (nsUniqs ns)
580 uniq = uniqFromSupply us1
581 new_local_name = mkInternalName uniq occ' loc
582 ns_w_local = ns { nsUniqs = us2 }
584 (ns_w_global, new_external_name) = newExternalName ns mod occ' loc
587 ------------ Worker --------------
588 tidyWorker tidy_env (HasWorker work_id wrap_arity)
589 = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
590 tidyWorker tidy_env other
594 %************************************************************************
596 \subsection{Figuring out CafInfo for an expression}
598 %************************************************************************
600 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
601 We mark such things as `MayHaveCafRefs' because this information is
602 used to decide whether a particular closure needs to be referenced
605 There are two reasons for setting MayHaveCafRefs:
606 a) The RHS is a CAF: a top-level updatable thunk.
607 b) The RHS refers to something that MayHaveCafRefs
609 Possible improvement: In an effort to keep the number of CAFs (and
610 hence the size of the SRTs) down, we could also look at the expression and
611 decide whether it requires a small bounded amount of heap, so we can ignore
612 it as a CAF. In these cases however, we would need to use an additional
613 CAF list to keep track of non-collectable CAFs.
616 hasCafRefs :: VarEnv Var -> Arity -> CoreExpr -> CafInfo
617 hasCafRefs p arity expr
618 | is_caf || mentions_cafs = MayHaveCafRefs
619 | otherwise = NoCafRefs
621 mentions_cafs = isFastTrue (cafRefs p expr)
622 is_caf = not (arity > 0 || rhsIsStatic expr)
623 -- NB. we pass in the arity of the expression, which is expected
624 -- to be calculated by exprArity. This is because exprArity
625 -- knows how much eta expansion is going to be done by
626 -- CorePrep later on, and we don't want to duplicate that
627 -- knowledge in rhsIsStatic below.
630 -- imported Ids first:
631 | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
632 -- now Ids local to this module:
634 case lookupVarEnv p id of
635 Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
636 Nothing -> fastBool False
638 cafRefs p (Lit l) = fastBool False
639 cafRefs p (App f a) = fastOr (cafRefs p f) (cafRefs p) a
640 cafRefs p (Lam x e) = cafRefs p e
641 cafRefs p (Let b e) = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
642 cafRefs p (Case e bndr alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
643 cafRefs p (Note n e) = cafRefs p e
644 cafRefs p (Type t) = fastBool False
646 cafRefss p [] = fastBool False
647 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
649 -- hack for lazy-or over FastBool.
650 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))