2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Tidying up Core}
8 tidyCorePgm, tidyExpr, tidyCoreExpr,
12 #include "HsVersions.h"
14 import CmdLineOpts ( DynFlags, DynFlag(..), opt_OmitInterfacePragmas )
16 import CoreUnfold ( noUnfolding, mkTopUnfolding, okToUnfoldInHiFile )
17 import CoreFVs ( ruleSomeFreeVars, exprSomeFreeVars,
19 import CoreLint ( showPass, endPass )
22 import Var ( Id, Var, varName )
23 import Id ( idType, idInfo, idName, isExportedId,
24 idSpecialisation, idUnique,
25 mkVanillaGlobal, isLocalId, isImplicitId,
26 hasNoBinding, mkUserLocal
28 import IdInfo {- loads of stuff -}
29 import Name ( getOccName, nameOccName, globaliseName, setNameOcc,
30 localiseName, isGlobalName, isLocalName
32 import NameEnv ( filterNameEnv )
33 import OccName ( TidyOccEnv, initTidyOccEnv, tidyOccName )
34 import Type ( tidyTopType, tidyType, tidyTyVar )
35 import Module ( Module, moduleName )
36 import HscTypes ( PersistentCompilerState( pcs_PRS ),
37 PersistentRenamerState( prsOrig ),
38 NameSupply( nsNames ), OrigNameCache,
39 TypeEnv, extendTypeEnvList,
40 ModDetails(..), TyThing(..)
42 import FiniteMap ( lookupFM, addToFM )
43 import Maybes ( maybeToBool, orElse )
44 import ErrUtils ( showPass )
45 import SrcLoc ( noSrcLoc )
46 import UniqFM ( mapUFM )
47 import List ( partition )
48 import Util ( mapAccumL )
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 - Make all external Ids have Global names and vice versa
84 This is used by the code generator to decide whether
85 to make the label externally visible
87 - Give external ids a "tidy" occurrence name. This means
88 we can print them in interface files without confusing
89 "x" (unique 5) with "x" (unique 10).
91 - Give external Ids the same Unique as they had before
92 if the name is in the renamer's name cache
94 - Give the Id its UTTERLY FINAL IdInfo; in ptic,
95 * Its IdDetails becomes VanillaGlobal, reflecting the fact that
96 from now on we regard it as a global, not local, Id
98 * its unfolding, if it should have one
100 * its arity, computed from the number of visible lambdas
102 * its CAF info, computed from what is free in its RHS
105 Finally, substitute these new top-level binders consistently
106 throughout, including in unfoldings. We also tidy binders in
107 RHSs, so that they print nicely in interfaces.
110 tidyCorePgm :: DynFlags -> Module
111 -> PersistentCompilerState
112 -> CgInfoEnv -- Information from the back end,
113 -- to be splatted into the IdInfo
115 -> IO (PersistentCompilerState, ModDetails)
117 tidyCorePgm dflags mod pcs cg_info_env
118 (ModDetails { md_types = env_tc, md_insts = insts_tc,
119 md_binds = binds_in, md_rules = orphans_in })
120 = do { showPass dflags "Tidy Core"
122 ; let ext_ids = findExternalSet binds_in orphans_in
123 ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
125 ; let ((orig_env', occ_env, subst_env), tidy_binds)
126 = mapAccumL (tidyTopBind mod ext_ids cg_info_env)
127 init_tidy_env binds_in
129 ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
131 ; let prs' = prs { prsOrig = orig { nsNames = orig_env' } }
132 pcs' = pcs { pcs_PRS = prs' }
134 ; let final_ids = [ id | bind <- tidy_binds
135 , id <- bindersOf bind
136 , isGlobalName (idName id)]
138 -- Dfuns are local Ids that might have
139 -- changed their unique during tidying
140 ; let lookup_dfun_id id = lookupVarEnv subst_env id `orElse`
141 pprPanic "lookup_dfun_id" (ppr id)
144 ; let tidy_type_env = mkFinalTypeEnv env_tc final_ids
145 tidy_dfun_ids = map lookup_dfun_id insts_tc
147 ; let tidy_details = ModDetails { md_types = tidy_type_env,
148 md_rules = tidy_rules,
149 md_insts = tidy_dfun_ids,
150 md_binds = tidy_binds }
152 ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
154 ; return (pcs', tidy_details)
157 -- We also make sure to avoid any exported binders. Consider
158 -- f{-u1-} = 1 -- Local decl
160 -- f{-u2-} = 2 -- Exported decl
162 -- The second exported decl must 'get' the name 'f', so we
163 -- have to put 'f' in the avoids list before we get to the first
164 -- decl. tidyTopId then does a no-op on exported binders.
167 orig_env = nsNames orig
169 init_tidy_env = (orig_env, initTidyOccEnv avoids, emptyVarEnv)
170 avoids = [getOccName bndr | bndr <- bindersOfBinds binds_in,
171 isGlobalName (idName bndr)]
173 tidyCoreExpr :: CoreExpr -> IO CoreExpr
174 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
178 %************************************************************************
180 \subsection{Write a new interface file}
182 %************************************************************************
185 mkFinalTypeEnv :: TypeEnv -- From typechecker
189 mkFinalTypeEnv type_env final_ids
190 = extendTypeEnvList (filterNameEnv keep_it type_env)
193 -- The competed type environment is gotten from
194 -- a) keeping the types and classes
195 -- b) removing all Ids,
196 -- c) adding Ids with correct IdInfo, including unfoldings,
197 -- gotten from the bindings
198 -- From (c) we keep only those Ids with Global names;
199 -- the CoreTidy pass makes sure these are all and only
200 -- the externally-accessible ones
201 -- This truncates the type environment to include only the
202 -- exported Ids and things needed from them, which saves space
204 -- However, we do keep things like constructors, which should not appear
205 -- in interface files, because they are needed by importing modules when
206 -- using the compilation manager
208 -- We keep constructor workers, because they won't appear
209 -- in the bindings from which final_ids are derived!
210 keep_it (AnId id) = hasNoBinding id -- Remove all Ids except constructor workers
211 keep_it other = True -- Keep all TyCons and Classes
215 findExternalRules :: [CoreBind]
216 -> [IdCoreRule] -- Orphan rules
217 -> IdEnv a -- Ids that are exported, so we need their rules
219 -- The complete rules are gotten by combining
220 -- a) the orphan rules
221 -- b) rules embedded in the top-level Ids
222 findExternalRules binds orphan_rules ext_ids
223 | opt_OmitInterfacePragmas = []
225 = orphan_rules ++ local_rules
227 local_rules = [ (id, rule)
228 | id <- bindersOfBinds binds,
229 id `elemVarEnv` ext_ids,
230 rule <- rulesRules (idSpecialisation id),
231 not (isBuiltinRule rule),
232 -- We can't print builtin rules in interface files
233 -- Since they are built in, an importing module
234 -- will have access to them anyway
236 -- Sept 00: I've disabled this test. It doesn't stop
237 -- many, if any, rules from coming out, and to make it
238 -- work properly we need to add ????
239 -- (put it back in for now)
240 isEmptyVarSet (ruleSomeLhsFreeVars (isLocalName . varName) rule)
242 -- Spit out a rule only if none of its LHS free
243 -- vars are LocalName things i.e. things that
244 -- aren't visible to importing modules This is a
245 -- good reason not to do it when we emit the Id
250 %************************************************************************
252 \subsection{Step 1: finding externals}
254 %************************************************************************
257 findExternalSet :: [CoreBind] -> [IdCoreRule]
258 -> IdEnv Bool -- In domain => external
259 -- Range = True <=> show unfolding
260 -- Step 1 from the notes above
261 findExternalSet binds orphan_rules
262 = foldr find init_needed binds
264 orphan_rule_ids :: IdSet
265 orphan_rule_ids = unionVarSets [ ruleSomeFreeVars isLocalId rule
266 | (_, rule) <- orphan_rules]
267 init_needed :: IdEnv Bool
268 init_needed = mapUFM (\_ -> False) orphan_rule_ids
269 -- The mapUFM is a bit cheesy. It is a cheap way
270 -- to turn the set of orphan_rule_ids, which we use to initialise
271 -- the sweep, into a mapping saying 'don't expose unfolding'
272 -- (When we come to the binding site we may change our mind, of course.)
274 find (NonRec id rhs) needed
275 | need_id needed id = addExternal (id,rhs) needed
277 find (Rec prs) needed = find_prs prs needed
279 -- For a recursive group we have to look for a fixed point
281 | null needed_prs = needed
282 | otherwise = find_prs other_prs new_needed
284 (needed_prs, other_prs) = partition (need_pr needed) prs
285 new_needed = foldr addExternal needed needed_prs
287 -- The 'needed' set contains the Ids that are needed by earlier
288 -- interface file emissions. If the Id isn't in this set, and isn't
289 -- exported, there's no need to emit anything
290 need_id needed_set id = id `elemVarEnv` needed_set || isExportedId id
291 need_pr needed_set (id,rhs) = need_id needed_set id
293 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
294 -- The Id is needed; extend the needed set
295 -- with it and its dependents (free vars etc)
296 addExternal (id,rhs) needed
297 = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
300 add_occ id needed = extendVarEnv needed id False
301 -- "False" because we don't know we need the Id's unfolding
302 -- We'll override it later when we find the binding site
304 new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
305 | otherwise = worker_ids `unionVarSet`
306 unfold_ids `unionVarSet`
310 dont_inline = isNeverInlinePrag (inlinePragInfo idinfo)
311 loop_breaker = isLoopBreaker (occInfo idinfo)
312 bottoming_fn = isBottomingStrictness (strictnessInfo idinfo)
313 spec_ids = rulesRhsFreeVars (specInfo idinfo)
314 worker_info = workerInfo idinfo
316 -- Stuff to do with the Id's unfolding
317 -- The simplifier has put an up-to-date unfolding
318 -- in the IdInfo, but the RHS will do just as well
319 unfolding = unfoldingInfo idinfo
320 rhs_is_small = not (neverUnfold unfolding)
322 -- We leave the unfolding there even if there is a worker
323 -- In GHCI the unfolding is used by importers
324 -- When writing an interface file, we omit the unfolding
325 -- if there is a worker
326 show_unfold = not bottoming_fn && -- Not necessary
329 rhs_is_small && -- Small enough
330 okToUnfoldInHiFile rhs -- No casms etc
332 unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
333 | otherwise = emptyVarSet
335 worker_ids = case worker_info of
336 HasWorker work_id _ -> unitVarSet work_id
337 otherwise -> emptyVarSet
341 %************************************************************************
343 \subsection{Step 2: top-level tidying}
345 %************************************************************************
349 type TopTidyEnv = (OrigNameCache, TidyOccEnv, VarEnv Var)
351 -- TopTidyEnv: when tidying we need to know
352 -- * orig_env: Any pre-ordained Names. These may have arisen because the
353 -- renamer read in an interface file mentioning M.$wf, say,
354 -- and assigned it unique r77. If, on this compilation, we've
355 -- invented an Id whose name is $wf (but with a different unique)
356 -- we want to rename it to have unique r77, so that we can do easy
357 -- comparisons with stuff from the interface file
359 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
362 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
367 tidyTopBind :: Module
368 -> IdEnv Bool -- Domain = Ids that should be external
369 -- True <=> their unfolding is external too
371 -> TopTidyEnv -> CoreBind
372 -> (TopTidyEnv, CoreBind)
374 tidyTopBind mod ext_ids cg_info_env top_tidy_env (NonRec bndr rhs)
375 = ((orig,occ,subst) , NonRec bndr' rhs')
377 ((orig,occ,subst), bndr')
378 = tidyTopBinder mod ext_ids cg_info_env rec_tidy_env rhs' top_tidy_env bndr
379 rec_tidy_env = (occ,subst)
380 rhs' = tidyExpr rec_tidy_env rhs
382 tidyTopBind mod ext_ids cg_info_env top_tidy_env (Rec prs)
383 = (final_env, Rec prs')
385 (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
386 rec_tidy_env = (occ,subst)
388 do_one top_tidy_env (bndr,rhs)
389 = ((orig,occ,subst), (bndr',rhs'))
391 ((orig,occ,subst), bndr')
392 = tidyTopBinder mod ext_ids cg_info_env
393 rec_tidy_env rhs' top_tidy_env bndr
395 rhs' = tidyExpr rec_tidy_env rhs
397 -- the CafInfo for a recursive group says whether *any* rhs in
398 -- the group may refer indirectly to a CAF (because then, they all do).
399 (bndrs, rhss) = unzip prs'
400 pred v = v `notElem` bndrs
403 tidyTopBinder :: Module -> IdEnv Bool
405 -> TidyEnv -> CoreExpr
406 -- The TidyEnv is used to tidy the IdInfo
407 -- The expr is the already-tided RHS
408 -- Both are knot-tied: don't look at them!
409 -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
410 -- NB: tidyTopBinder doesn't affect the unique supply
412 tidyTopBinder mod ext_ids cg_info_env tidy_env rhs
413 env@(orig_env2, occ_env2, subst_env2) id
415 | isImplicitId id -- Don't mess with constructors,
416 = (env, id) -- record selectors, and the like
419 -- This function is the heart of Step 2
420 -- The second env is the one to use for the IdInfo
421 -- It's necessary because when we are dealing with a recursive
422 -- group, a variable late in the group might be mentioned
423 -- in the IdInfo of one early in the group
425 -- The rhs is already tidied
427 = ((orig_env', occ_env', subst_env'), id')
429 (orig_env', occ_env', name') = tidyTopName mod orig_env2 occ_env2
432 ty' = tidyTopType (idType id)
433 cg_info = lookupCgInfo cg_info_env name'
434 idinfo' = tidyIdInfo tidy_env is_external unfold_info cg_info id
436 id' = mkVanillaGlobal name' ty' idinfo'
437 subst_env' = extendVarEnv subst_env2 id id'
439 maybe_external = lookupVarEnv ext_ids id
440 is_external = maybeToBool maybe_external
442 -- Expose an unfolding if ext_ids tells us to
443 show_unfold = maybe_external `orElse` False
444 unfold_info | show_unfold = mkTopUnfolding rhs
445 | otherwise = noUnfolding
448 tidyIdInfo tidy_env is_external unfold_info cg_info id
449 | opt_OmitInterfacePragmas || not is_external
450 -- No IdInfo if the Id isn't external, or if we don't have -O
453 `setStrictnessInfo` strictnessInfo core_idinfo
454 -- Keep strictness; it's used by CorePrep
459 `setCprInfo` cprInfo core_idinfo
460 `setStrictnessInfo` strictnessInfo core_idinfo
461 `setInlinePragInfo` inlinePragInfo core_idinfo
462 `setUnfoldingInfo` unfold_info
463 `setWorkerInfo` tidyWorker tidy_env (workerInfo core_idinfo)
464 -- NB: we throw away the Rules
465 -- They have already been extracted by findExternalRules
467 core_idinfo = idInfo id
470 -- This is where we set names to local/global based on whether they really are
471 -- externally visible (see comment at the top of this module). If the name
472 -- was previously local, we have to give it a unique occurrence name if
473 -- we intend to globalise it.
474 tidyTopName mod orig_env occ_env external name
475 | global && internal = (orig_env, occ_env, localiseName name)
477 | local && internal = (orig_env, occ_env', setNameOcc name occ')
478 -- Even local, internal names must get a unique occurrence, because
479 -- if we do -split-objs we globalise the name later, n the code generator
481 | global && external = (orig_env, occ_env, name)
482 -- Global names are assumed to have been allocated by the renamer,
483 -- so they already have the "right" unique
485 | local && external = case lookupFM orig_env key of
486 Just orig -> (orig_env, occ_env', orig)
487 Nothing -> (addToFM orig_env key global_name, occ_env', global_name)
488 -- If we want to globalise a currently-local name, check
489 -- whether we have already assigned a unique for it.
490 -- If so, use it; if not, extend the table
493 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
494 key = (moduleName mod, occ')
495 global_name = globaliseName (setNameOcc name occ') mod
496 global = isGlobalName name
498 internal = not external
500 ------------ Worker --------------
501 tidyWorker tidy_env (HasWorker work_id wrap_arity)
502 = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
503 tidyWorker tidy_env other
506 ------------ Rules --------------
507 tidyIdRules :: TidyEnv -> [IdCoreRule] -> [IdCoreRule]
508 tidyIdRules env [] = []
509 tidyIdRules env ((fn,rule) : rules)
510 = tidyRule env rule =: \ rule ->
511 tidyIdRules env rules =: \ rules ->
512 ((tidyVarOcc env fn, rule) : rules)
514 tidyRule :: TidyEnv -> CoreRule -> CoreRule
515 tidyRule env rule@(BuiltinRule _) = rule
516 tidyRule env (Rule name vars tpl_args rhs)
517 = tidyBndrs env vars =: \ (env', vars) ->
518 map (tidyExpr env') tpl_args =: \ tpl_args ->
519 (Rule name vars tpl_args (tidyExpr env' rhs))
522 %************************************************************************
524 \subsection{Step 2: inner tidying
526 %************************************************************************
531 -> (TidyEnv, CoreBind)
533 tidyBind env (NonRec bndr rhs)
534 = tidyBndrWithRhs env (bndr,rhs) =: \ (env', bndr') ->
535 (env', NonRec bndr' (tidyExpr env' rhs))
537 tidyBind env (Rec prs)
538 = mapAccumL tidyBndrWithRhs env prs =: \ (env', bndrs') ->
539 map (tidyExpr env') (map snd prs) =: \ rhss' ->
540 (env', Rec (zip bndrs' rhss'))
543 tidyExpr env (Var v) = Var (tidyVarOcc env v)
544 tidyExpr env (Type ty) = Type (tidyType env ty)
545 tidyExpr env (Lit lit) = Lit lit
546 tidyExpr env (App f a) = App (tidyExpr env f) (tidyExpr env a)
547 tidyExpr env (Note n e) = Note (tidyNote env n) (tidyExpr env e)
549 tidyExpr env (Let b e)
550 = tidyBind env b =: \ (env', b') ->
551 Let b' (tidyExpr env' e)
553 tidyExpr env (Case e b alts)
554 = tidyBndr env b =: \ (env', b) ->
555 Case (tidyExpr env e) b (map (tidyAlt env') alts)
557 tidyExpr env (Lam b e)
558 = tidyBndr env b =: \ (env', b) ->
559 Lam b (tidyExpr env' e)
562 tidyAlt env (con, vs, rhs)
563 = tidyBndrs env vs =: \ (env', vs) ->
564 (con, vs, tidyExpr env' rhs)
566 tidyNote env (Coerce t1 t2) = Coerce (tidyType env t1) (tidyType env t2)
567 tidyNote env note = note
571 %************************************************************************
573 \subsection{Tidying up non-top-level binders}
575 %************************************************************************
578 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
582 -- tidyBndr is used for lambda and case binders
583 tidyBndr :: TidyEnv -> Var -> (TidyEnv, Var)
585 | isTyVar var = tidyTyVar env var
586 | otherwise = tidyId env var
588 tidyBndrs :: TidyEnv -> [Var] -> (TidyEnv, [Var])
589 tidyBndrs env vars = mapAccumL tidyBndr env vars
591 -- tidyBndrWithRhs is used for let binders
592 tidyBndrWithRhs :: TidyEnv -> (Id, CoreExpr) -> (TidyEnv, Var)
593 tidyBndrWithRhs env (id,rhs) = tidyId env id
595 tidyId :: TidyEnv -> Id -> (TidyEnv, Id)
596 tidyId env@(tidy_env, var_env) id
597 = -- Non-top-level variables
599 -- Give the Id a fresh print-name, *and* rename its type
600 -- The SrcLoc isn't important now,
601 -- though we could extract it from the Id
603 -- All local Ids now have the same IdInfo, which should save some
605 (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
606 ty' = tidyType (tidy_env,var_env) (idType id)
607 id' = mkUserLocal occ' (idUnique id) ty' noSrcLoc
608 var_env' = extendVarEnv var_env id id'
610 ((tidy_env', var_env'), id')