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 )
18 import CoreLint ( showPass, endPass )
21 import Var ( Id, Var )
22 import Id ( idType, idInfo, idName, isExportedId,
23 idSpecialisation, idUnique, isDataConWrapId,
24 mkVanillaGlobal, isLocalId, isRecordSelector,
25 setIdUnfolding, hasNoBinding, mkUserLocal,
26 idNewDemandInfo, setIdNewDemandInfo
28 import IdInfo {- loads of stuff -}
29 import NewDemand ( isBottomingSig, topSig, isStrictDmd )
30 import Name ( getOccName, nameOccName, globaliseName, setNameOcc,
31 localiseName, isGlobalName, setNameUnique
33 import NameEnv ( filterNameEnv )
34 import OccName ( TidyOccEnv, initTidyOccEnv, tidyOccName )
35 import Type ( tidyTopType, tidyType, tidyTyVar )
36 import Module ( Module, moduleName )
37 import HscTypes ( PersistentCompilerState( pcs_PRS ),
38 PersistentRenamerState( prsOrig ),
39 NameSupply( nsNames, nsUniqs ),
40 TypeEnv, extendTypeEnvList,
41 ModDetails(..), TyThing(..)
43 import FiniteMap ( lookupFM, addToFM )
44 import Maybes ( maybeToBool, orElse )
45 import ErrUtils ( showPass )
46 import SrcLoc ( noSrcLoc )
47 import UniqFM ( mapUFM )
48 import UniqSupply ( splitUniqSupply, uniqFromSupply )
49 import List ( partition )
50 import Util ( mapAccumL )
56 %************************************************************************
58 \subsection{What goes on}
60 %************************************************************************
66 Step 1: Figure out external Ids
67 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68 First we figure out which Ids are "external" Ids. An
69 "external" Id is one that is visible from outside the compilation
71 a) the user exported ones
72 b) ones mentioned in the unfoldings, workers,
73 or rules of externally-visible ones
74 This exercise takes a sweep of the bindings bottom to top. Actually,
75 in Step 2 we're also going to need to know which Ids should be
76 exported with their unfoldings, so we produce not an IdSet but an
80 Step 2: Tidy the program
81 ~~~~~~~~~~~~~~~~~~~~~~~~
82 Next we traverse the bindings top to bottom. For each *top-level*
85 1. Make it into a GlobalId
87 2. Give it a system-wide Unique.
88 [Even non-exported things need system-wide Uniques because the
89 byte-code generator builds a single Name->BCO symbol table.]
91 We use the NameSupply kept in the PersistentRenamerState as the
92 source of such system-wide uniques.
94 For external Ids, use the original-name cache in the NameSupply
95 to ensure that the unique assigned is the same as the Id had
96 in any previous compilation run.
98 3. If it's an external Id, make it have a global Name, otherwise
99 make it have a local Name.
100 This is used by the code generator to decide whether
101 to make the label externally visible
103 4. Give external Ids a "tidy" occurrence name. This means
104 we can print them in interface files without confusing
105 "x" (unique 5) with "x" (unique 10).
107 5. Give it its UTTERLY FINAL IdInfo; in ptic,
108 * Its IdDetails becomes VanillaGlobal, reflecting the fact that
109 from now on we regard it as a global, not local, Id
111 * its unfolding, if it should have one
113 * its arity, computed from the number of visible lambdas
115 * its CAF info, computed from what is free in its RHS
118 Finally, substitute these new top-level binders consistently
119 throughout, including in unfoldings. We also tidy binders in
120 RHSs, so that they print nicely in interfaces.
123 tidyCorePgm :: DynFlags -> Module
124 -> PersistentCompilerState
125 -> CgInfoEnv -- Information from the back end,
126 -- to be splatted into the IdInfo
128 -> IO (PersistentCompilerState, ModDetails)
130 tidyCorePgm dflags mod pcs cg_info_env
131 (ModDetails { md_types = env_tc, md_insts = insts_tc,
132 md_binds = binds_in, md_rules = orphans_in })
133 = do { showPass dflags "Tidy Core"
135 ; let ext_ids = findExternalSet binds_in orphans_in
136 ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
138 -- We also make sure to avoid any exported binders. Consider
139 -- f{-u1-} = 1 -- Local decl
141 -- f{-u2-} = 2 -- Exported decl
143 -- The second exported decl must 'get' the name 'f', so we
144 -- have to put 'f' in the avoids list before we get to the first
145 -- decl. tidyTopId then does a no-op on exported binders.
146 ; let prs = pcs_PRS pcs
147 orig_ns = prsOrig prs
149 init_tidy_env = (orig_ns, initTidyOccEnv avoids, emptyVarEnv)
150 avoids = [getOccName bndr | bndr <- bindersOfBinds binds_in,
151 isGlobalName (idName bndr)]
153 ; let ((orig_ns', occ_env, subst_env), tidy_binds)
154 = mapAccumL (tidyTopBind mod ext_ids cg_info_env)
155 init_tidy_env binds_in
157 ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
159 ; let prs' = prs { prsOrig = orig_ns' }
160 pcs' = pcs { pcs_PRS = prs' }
162 ; let final_ids = [ id | bind <- tidy_binds
163 , id <- bindersOf bind
164 , isGlobalName (idName id)]
166 -- Dfuns are local Ids that might have
167 -- changed their unique during tidying
168 ; let lookup_dfun_id id = lookupVarEnv subst_env id `orElse`
169 pprPanic "lookup_dfun_id" (ppr id)
172 ; let tidy_type_env = mkFinalTypeEnv env_tc final_ids
173 tidy_dfun_ids = map lookup_dfun_id insts_tc
175 ; let tidy_details = ModDetails { md_types = tidy_type_env,
176 md_rules = tidy_rules,
177 md_insts = tidy_dfun_ids,
178 md_binds = tidy_binds }
180 ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
182 ; return (pcs', tidy_details)
185 tidyCoreExpr :: CoreExpr -> IO CoreExpr
186 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
190 %************************************************************************
192 \subsection{Write a new interface file}
194 %************************************************************************
197 mkFinalTypeEnv :: TypeEnv -- From typechecker
201 mkFinalTypeEnv type_env final_ids
202 = extendTypeEnvList (filterNameEnv keep_it type_env)
205 -- The competed type environment is gotten from
206 -- a) keeping the types and classes
207 -- b) removing all Ids,
208 -- c) adding Ids with correct IdInfo, including unfoldings,
209 -- gotten from the bindings
210 -- From (c) we keep only those Ids with Global names;
211 -- the CoreTidy pass makes sure these are all and only
212 -- the externally-accessible ones
213 -- This truncates the type environment to include only the
214 -- exported Ids and things needed from them, which saves space
216 -- However, we do keep things like constructors, which should not appear
217 -- in interface files, because they are needed by importing modules when
218 -- using the compilation manager
220 -- We keep "hasNoBinding" Ids, notably constructor workers,
221 -- because they won't appear in the bindings from which final_ids are derived!
222 keep_it (AnId id) = hasNoBinding id -- Remove all Ids except constructor workers
223 keep_it other = True -- Keep all TyCons and Classes
227 findExternalRules :: [CoreBind]
228 -> [IdCoreRule] -- Orphan rules
229 -> IdEnv a -- Ids that are exported, so we need their rules
231 -- The complete rules are gotten by combining
232 -- a) the orphan rules
233 -- b) rules embedded in the top-level Ids
234 findExternalRules binds orphan_rules ext_ids
235 | opt_OmitInterfacePragmas = []
237 = orphan_rules ++ local_rules
239 local_rules = [ (id, rule)
240 | id <- bindersOfBinds binds,
241 id `elemVarEnv` ext_ids,
242 rule <- rulesRules (idSpecialisation id),
243 not (isBuiltinRule rule)
244 -- We can't print builtin rules in interface files
245 -- Since they are built in, an importing module
246 -- will have access to them anyway
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 = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
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 = (NameSupply, TidyOccEnv, VarEnv Var)
351 -- TopTidyEnv: when tidying we need to know
352 -- * ns: The NameSupply, containing a unique supply and any pre-ordained Names.
353 -- These may have arisen because the
354 -- renamer read in an interface file mentioning M.$wf, say,
355 -- and assigned it unique r77. If, on this compilation, we've
356 -- invented an Id whose name is $wf (but with a different unique)
357 -- we want to rename it to have unique r77, so that we can do easy
358 -- comparisons with stuff from the interface file
360 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
363 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
368 tidyTopBind :: Module
369 -> IdEnv Bool -- Domain = Ids that should be external
370 -- True <=> their unfolding is external too
372 -> TopTidyEnv -> CoreBind
373 -> (TopTidyEnv, CoreBind)
375 tidyTopBind mod ext_ids cg_info_env top_tidy_env (NonRec bndr rhs)
376 = ((orig,occ,subst) , NonRec bndr' rhs')
378 ((orig,occ,subst), bndr')
379 = tidyTopBinder mod ext_ids cg_info_env rec_tidy_env rhs' top_tidy_env bndr
380 rec_tidy_env = (occ,subst)
381 rhs' = tidyExpr rec_tidy_env rhs
383 tidyTopBind mod ext_ids cg_info_env top_tidy_env (Rec prs)
384 = (final_env, Rec prs')
386 (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
387 rec_tidy_env = (occ,subst)
389 do_one top_tidy_env (bndr,rhs)
390 = ((orig,occ,subst), (bndr',rhs'))
392 ((orig,occ,subst), bndr')
393 = tidyTopBinder mod ext_ids cg_info_env
394 rec_tidy_env rhs' top_tidy_env bndr
396 rhs' = tidyExpr rec_tidy_env rhs
398 tidyTopBinder :: Module -> IdEnv Bool
400 -> TidyEnv -> CoreExpr
401 -- The TidyEnv is used to tidy the IdInfo
402 -- The expr is the already-tided RHS
403 -- Both are knot-tied: don't look at them!
404 -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
405 -- NB: tidyTopBinder doesn't affect the unique supply
407 tidyTopBinder mod ext_ids cg_info_env tidy_env rhs
408 env@(ns2, occ_env2, subst_env2) id
410 | isDataConWrapId id -- Don't tidy constructor wrappers
411 = (env, id) -- The Id is stored in the TyCon, so it would be bad
412 -- if anything changed
414 -- HACK ALERT: we *do* tidy record selectors. Reason: they mention error
415 -- messages, which may be floated out:
416 -- x_field pt = case pt of
418 -- Pol _ _ -> error "buggle wuggle"
419 -- The error message will be floated out so we'll get
420 -- lvl5 = error "buggle wuggle"
421 -- x_field pt = case pt of
425 -- When this happens, it's vital that the Id exposed to importing modules
426 -- (by ghci) mentions lvl5 in its unfolding, not the un-tidied version.
428 -- What about the Id in the TyCon? It probably shouldn't be in the TyCon at
429 -- all, but in any case it will have the error message inline so it won't matter.
432 | isRecordSelector id -- We can't use the "otherwise" case, because that
433 -- forgets the IdDetails, which forgets that this is
434 -- a record selector, which confuses an importing module
435 = (env, id `setIdUnfolding` unfold_info)
438 -- This function is the heart of Step 2
439 -- The second env is the one to use for the IdInfo
440 -- It's necessary because when we are dealing with a recursive
441 -- group, a variable late in the group might be mentioned
442 -- in the IdInfo of one early in the group
444 -- The rhs is already tidied
446 = ((orig_env', occ_env', subst_env'), id')
448 (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
451 ty' = tidyTopType (idType id)
452 cg_info = lookupCgInfo cg_info_env name'
453 idinfo' = tidyIdInfo tidy_env is_external unfold_info cg_info id
455 id' = mkVanillaGlobal name' ty' idinfo'
456 subst_env' = extendVarEnv subst_env2 id id'
458 maybe_external = lookupVarEnv ext_ids id
459 is_external = maybeToBool maybe_external
461 -- Expose an unfolding if ext_ids tells us to
462 show_unfold = maybe_external `orElse` False
463 unfold_info | show_unfold = mkTopUnfolding rhs
464 | otherwise = noUnfolding
467 tidyIdInfo tidy_env is_external unfold_info cg_info id
468 | opt_OmitInterfacePragmas || not is_external
469 -- No IdInfo if the Id isn't external, or if we don't have -O
472 `setNewStrictnessInfo` newStrictnessInfo core_idinfo
473 -- Keep strictness; it's used by CorePrep
478 `setNewStrictnessInfo` newStrictnessInfo core_idinfo
479 `setInlinePragInfo` inlinePragInfo core_idinfo
480 `setUnfoldingInfo` unfold_info
481 `setWorkerInfo` tidyWorker tidy_env (workerInfo core_idinfo)
482 -- NB: we throw away the Rules
483 -- They have already been extracted by findExternalRules
485 core_idinfo = idInfo id
488 -- This is where we set names to local/global based on whether they really are
489 -- externally visible (see comment at the top of this module). If the name
490 -- was previously local, we have to give it a unique occurrence name if
491 -- we intend to globalise it.
492 tidyTopName mod ns occ_env external name
493 | global && internal = (ns, occ_env, localiseName name)
495 | global && external = (ns, occ_env, name)
496 -- Global names are assumed to have been allocated by the renamer,
497 -- so they already have the "right" unique
498 -- And it's a system-wide unique too
500 | local && internal = (ns { nsUniqs = us2 }, occ_env', unique_name)
501 -- Even local, internal names must get a unique occurrence, because
502 -- if we do -split-objs we globalise the name later, in the code generator
504 -- Similarly, we must make sure it has a system-wide Unique, because
505 -- the byte-code generator builds a system-wide Name->BCO symbol table
507 | local && external = case lookupFM ns_names key of
508 Just orig -> (ns, occ_env', orig)
509 Nothing -> (ns { nsUniqs = us2, nsNames = ns_names' }, occ_env', global_name)
510 -- If we want to globalise a currently-local name, check
511 -- whether we have already assigned a unique for it.
512 -- If so, use it; if not, extend the table
515 global = isGlobalName name
517 internal = not external
519 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
520 key = (moduleName mod, occ')
521 ns_names = nsNames ns
522 ns_uniqs = nsUniqs ns
523 (us1, us2) = splitUniqSupply ns_uniqs
524 unique_name = setNameUnique (setNameOcc name occ') (uniqFromSupply us1)
525 global_name = globaliseName unique_name mod
526 ns_names' = addToFM ns_names key global_name
529 ------------ Worker --------------
530 tidyWorker tidy_env (HasWorker work_id wrap_arity)
531 = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
532 tidyWorker tidy_env other
535 ------------ Rules --------------
536 tidyIdRules :: TidyEnv -> [IdCoreRule] -> [IdCoreRule]
537 tidyIdRules env [] = []
538 tidyIdRules env ((fn,rule) : rules)
539 = tidyRule env rule =: \ rule ->
540 tidyIdRules env rules =: \ rules ->
541 ((tidyVarOcc env fn, rule) : rules)
543 tidyRule :: TidyEnv -> CoreRule -> CoreRule
544 tidyRule env rule@(BuiltinRule _ _) = rule
545 tidyRule env (Rule name vars tpl_args rhs)
546 = tidyBndrs env vars =: \ (env', vars) ->
547 map (tidyExpr env') tpl_args =: \ tpl_args ->
548 (Rule name vars tpl_args (tidyExpr env' rhs))
551 %************************************************************************
553 \subsection{Step 2: inner tidying
555 %************************************************************************
560 -> (TidyEnv, CoreBind)
562 tidyBind env (NonRec bndr rhs)
563 = tidyBndrWithRhs env (bndr,rhs) =: \ (env', bndr') ->
564 (env', NonRec bndr' (tidyExpr env' rhs))
566 tidyBind env (Rec prs)
567 = mapAccumL tidyBndrWithRhs env prs =: \ (env', bndrs') ->
568 map (tidyExpr env') (map snd prs) =: \ rhss' ->
569 (env', Rec (zip bndrs' rhss'))
572 tidyExpr env (Var v) = Var (tidyVarOcc env v)
573 tidyExpr env (Type ty) = Type (tidyType env ty)
574 tidyExpr env (Lit lit) = Lit lit
575 tidyExpr env (App f a) = App (tidyExpr env f) (tidyExpr env a)
576 tidyExpr env (Note n e) = Note (tidyNote env n) (tidyExpr env e)
578 tidyExpr env (Let b e)
579 = tidyBind env b =: \ (env', b') ->
580 Let b' (tidyExpr env' e)
582 tidyExpr env (Case e b alts)
583 = tidyBndr env b =: \ (env', b) ->
584 Case (tidyExpr env e) b (map (tidyAlt env') alts)
586 tidyExpr env (Lam b e)
587 = tidyBndr env b =: \ (env', b) ->
588 Lam b (tidyExpr env' e)
591 tidyAlt env (con, vs, rhs)
592 = tidyBndrs env vs =: \ (env', vs) ->
593 (con, vs, tidyExpr env' rhs)
595 tidyNote env (Coerce t1 t2) = Coerce (tidyType env t1) (tidyType env t2)
596 tidyNote env note = note
600 %************************************************************************
602 \subsection{Tidying up non-top-level binders}
604 %************************************************************************
607 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
611 -- tidyBndr is used for lambda and case binders
612 tidyBndr :: TidyEnv -> Var -> (TidyEnv, Var)
614 | isTyVar var = tidyTyVar env var
615 | otherwise = tidyId env var
617 tidyBndrs :: TidyEnv -> [Var] -> (TidyEnv, [Var])
618 tidyBndrs env vars = mapAccumL tidyBndr env vars
620 -- tidyBndrWithRhs is used for let binders
621 tidyBndrWithRhs :: TidyEnv -> (Id, CoreExpr) -> (TidyEnv, Var)
622 tidyBndrWithRhs env (id,rhs)
623 = add_dmd_info (tidyId env id)
625 -- We add demand info for let(rec) binders, because
626 -- that's what tells CorePrep to generate a case instead of a thunk
627 add_dmd_info (env,new_id)
628 | isStrictDmd dmd_info = (env, setIdNewDemandInfo new_id dmd_info)
629 | otherwise = (env, new_id)
630 dmd_info = idNewDemandInfo id
632 tidyId :: TidyEnv -> Id -> (TidyEnv, Id)
633 tidyId env@(tidy_env, var_env) id
634 = -- Non-top-level variables
636 -- Give the Id a fresh print-name, *and* rename its type
637 -- The SrcLoc isn't important now,
638 -- though we could extract it from the Id
640 -- All local Ids now have the same IdInfo, which should save some
642 (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
643 ty' = tidyType (tidy_env,var_env) (idType id)
644 id' = mkUserLocal occ' (idUnique id) ty' noSrcLoc
645 var_env' = extendVarEnv var_env id id'
647 ((tidy_env', var_env'), id')