2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Tidying up Core}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 module TidyPgm( mkBootModDetails, tidyProgram ) where
16 #include "HsVersions.h"
18 import DynFlags ( DynFlag(..), DynFlags(..), dopt )
20 import CoreUnfold ( noUnfolding, mkTopUnfolding )
21 import CoreFVs ( ruleLhsFreeIds, exprSomeFreeVars )
22 import CoreTidy ( tidyExpr, tidyVarOcc, tidyRules )
23 import PprCore ( pprRules )
24 import CoreLint ( showPass, endPass )
25 import CoreUtils ( exprArity, rhsIsStatic )
28 import Var ( Id, Var )
29 import Id ( idType, idInfo, idName, idCoreRules, isGlobalId,
30 isExportedId, mkVanillaGlobal, isLocalId, isNaughtyRecordSelector,
31 idArity, idCafInfo, idUnfolding, isImplicitId, setIdInfo,
34 import IdInfo {- loads of stuff -}
35 import InstEnv ( Instance, DFunId, instanceDFunId, setInstanceDFunId )
36 import NewDemand ( isBottomingSig, topSig )
37 import BasicTypes ( Arity, isNeverActive, isNonRuleLoopBreaker )
39 import NameSet ( NameSet, elemNameSet )
40 import IfaceEnv ( allocateGlobalBinder )
41 import NameEnv ( filterNameEnv, mapNameEnv )
42 import OccName ( TidyOccEnv, initTidyOccEnv, tidyOccName )
43 import Type ( tidyTopType )
44 import TcType ( isFFITy )
45 import DataCon ( dataConName, dataConFieldLabels, dataConWrapId_maybe )
46 import TyCon ( TyCon, makeTyConAbstract, tyConDataCons, isNewTyCon,
47 newTyConRep, tyConSelIds, isAlgTyCon,
48 isEnumerationTyCon, isOpenTyCon )
49 import Class ( classSelIds )
52 import Maybes ( orElse, mapCatMaybes )
53 import ErrUtils ( showPass, dumpIfSet_core )
54 import UniqSupply ( splitUniqSupply, uniqFromSupply )
56 import FastTypes hiding ( fastOr )
58 import Data.List ( partition )
59 import Data.Maybe ( isJust )
60 import Data.IORef ( IORef, readIORef, writeIORef )
64 Constructing the TypeEnv, Instances, Rules from which the ModIface is
65 constructed, and which goes on to subsequent modules in --make mode.
67 Most of the interface file is obtained simply by serialising the
68 TypeEnv. One important consequence is that if the *interface file*
69 has pragma info if and only if the final TypeEnv does. This is not so
70 important for *this* module, but it's essential for ghc --make:
71 subsequent compilations must not see (e.g.) the arity if the interface
72 file does not contain arity If they do, they'll exploit the arity;
73 then the arity might change, but the iface file doesn't change =>
74 recompilation does not happen => disaster.
76 For data types, the final TypeEnv will have a TyThing for the TyCon,
77 plus one for each DataCon; the interface file will contain just one
78 data type declaration, but it is de-serialised back into a collection
81 %************************************************************************
85 %************************************************************************
88 Plan A: mkBootModDetails: omit pragmas, make interfaces small
89 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92 * Drop all WiredIn things from the TypeEnv
93 (we never want them in interface files)
95 * Retain all TyCons and Classes in the TypeEnv, to avoid
96 having to find which ones are mentioned in the
99 * Trim off the constructors of non-exported TyCons, both
100 from the TyCon and from the TypeEnv
102 * Drop non-exported Ids from the TypeEnv
104 * Tidy the types of the DFunIds of Instances,
105 make them into GlobalIds, (they already have External Names)
106 and add them to the TypeEnv
108 * Tidy the types of the (exported) Ids in the TypeEnv,
109 make them into GlobalIds (they already have External Names)
111 * Drop rules altogether
113 * Tidy the bindings, to ensure that the Caf and Arity
114 information is correct for each top-level binder; the
115 code generator needs it. And to ensure that local names have
116 distinct OccNames in case of object-file splitting
119 mkBootModDetails :: HscEnv -> ModGuts -> IO ModDetails
120 -- This is Plan A: make a small type env when typechecking only,
121 -- or when compiling a hs-boot file, or simply when not using -O
123 -- We don't look at the bindings at all -- there aren't any
126 mkBootModDetails hsc_env (ModGuts { mg_module = mod
127 , mg_exports = exports
128 , mg_types = type_env
130 , mg_fam_insts = fam_insts
131 , mg_modBreaks = modBreaks
133 = do { let dflags = hsc_dflags hsc_env
134 ; showPass dflags "Tidy [hoot] type env"
136 ; let { insts' = tidyInstances tidyExternalId insts
137 ; type_env1 = filterNameEnv (not . isWiredInThing) type_env
138 ; type_env2 = mapNameEnv tidyBootThing type_env1
139 ; type_env' = extendTypeEnvWithIds type_env2
140 (map instanceDFunId insts')
142 ; return (ModDetails { md_types = type_env'
144 , md_fam_insts = fam_insts
146 , md_exports = exports
147 , md_vect_info = noVectInfo
152 isWiredInThing :: TyThing -> Bool
153 isWiredInThing thing = isWiredInName (getName thing)
155 tidyBootThing :: TyThing -> TyThing
156 -- Just externalise the Ids; keep everything
157 tidyBootThing (AnId id) | isLocalId id = AnId (tidyExternalId id)
158 tidyBootThing thing = thing
160 tidyExternalId :: Id -> Id
161 -- Takes an LocalId with an External Name,
162 -- makes it into a GlobalId with VanillaIdInfo, and tidies its type
163 -- (NB: vanillaIdInfo makes a conservative assumption about Caf-hood.)
165 = ASSERT2( isLocalId id && isExternalName (idName id), ppr id )
166 mkVanillaGlobal (idName id) (tidyTopType (idType id)) vanillaIdInfo
170 %************************************************************************
172 Plan B: tidy bindings, make TypeEnv full of IdInfo
174 %************************************************************************
176 Plan B: include pragmas, make interfaces
177 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178 * Figure out which Ids are externally visible
180 * Tidy the bindings, externalising appropriate Ids
182 * Drop all Ids from the TypeEnv, and add all the External Ids from
183 the bindings. (This adds their IdInfo to the TypeEnv; and adds
184 floated-out Ids that weren't even in the TypeEnv before.)
186 Step 1: Figure out external Ids
187 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
188 First we figure out which Ids are "external" Ids. An
189 "external" Id is one that is visible from outside the compilation
191 a) the user exported ones
192 b) ones mentioned in the unfoldings, workers,
193 or rules of externally-visible ones
194 This exercise takes a sweep of the bindings bottom to top. Actually,
195 in Step 2 we're also going to need to know which Ids should be
196 exported with their unfoldings, so we produce not an IdSet but an
200 Step 2: Tidy the program
201 ~~~~~~~~~~~~~~~~~~~~~~~~
202 Next we traverse the bindings top to bottom. For each *top-level*
205 1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal,
206 reflecting the fact that from now on we regard it as a global,
209 2. Give it a system-wide Unique.
210 [Even non-exported things need system-wide Uniques because the
211 byte-code generator builds a single Name->BCO symbol table.]
213 We use the NameCache kept in the HscEnv as the
214 source of such system-wide uniques.
216 For external Ids, use the original-name cache in the NameCache
217 to ensure that the unique assigned is the same as the Id had
218 in any previous compilation run.
220 3. If it's an external Id, make it have a External Name, otherwise
221 make it have an Internal Name.
222 This is used by the code generator to decide whether
223 to make the label externally visible
225 4. Give external Ids a "tidy" OccName. This means
226 we can print them in interface files without confusing
227 "x" (unique 5) with "x" (unique 10).
229 5. Give it its UTTERLY FINAL IdInfo; in ptic,
230 * its unfolding, if it should have one
232 * its arity, computed from the number of visible lambdas
234 * its CAF info, computed from what is free in its RHS
237 Finally, substitute these new top-level binders consistently
238 throughout, including in unfoldings. We also tidy binders in
239 RHSs, so that they print nicely in interfaces.
242 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
244 mod_impl@(ModGuts { mg_module = mod, mg_exports = exports,
246 mg_insts = insts, mg_fam_insts = fam_insts,
248 mg_rules = imp_rules,
249 mg_vect_info = vect_info,
250 mg_dir_imps = dir_imps, mg_deps = deps,
251 mg_foreign = foreign_stubs,
252 mg_hpc_info = hpc_info,
253 mg_modBreaks = modBreaks })
255 = do { let dflags = hsc_dflags hsc_env
256 ; showPass dflags "Tidy Core"
258 ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
259 ; ext_ids = findExternalIds omit_prags binds
262 | otherwise = findExternalRules binds imp_rules ext_ids
263 -- findExternalRules filters imp_rules to avoid binders that
264 -- aren't externally visible; but the externally-visible binders
265 -- are computed (by findExternalIds) assuming that all orphan
266 -- rules are exported (they get their Exported flag set in the desugarer)
267 -- So in fact we may export more than we need.
268 -- (It's a sort of mutual recursion.)
271 ; (tidy_env, tidy_binds) <- tidyTopBinds hsc_env mod type_env ext_ids
274 ; let { export_set = availsToNameSet exports
275 ; tidy_type_env = tidyTypeEnv omit_prags export_set type_env
277 ; tidy_insts = tidyInstances (lookup_dfun tidy_type_env) insts
278 -- A DFunId will have a binding in tidy_binds, and so
279 -- will now be in final_env, replete with IdInfo
280 -- Its name will be unchanged since it was born, but
281 -- we want Global, IdInfo-rich (or not) DFunId in the
284 ; tidy_rules = tidyRules tidy_env ext_rules
285 -- You might worry that the tidy_env contains IdInfo-rich stuff
286 -- and indeed it does, but if omit_prags is on, ext_rules is
289 ; implicit_binds = getImplicitBinds type_env
290 ; all_tidy_binds = implicit_binds ++ tidy_binds
291 ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
294 ; endPass dflags "Tidy Core" Opt_D_dump_simpl all_tidy_binds
295 ; dumpIfSet_core dflags Opt_D_dump_simpl
297 (pprRules tidy_rules)
299 ; return (CgGuts { cg_module = mod,
300 cg_tycons = alg_tycons,
301 cg_binds = all_tidy_binds,
302 cg_dir_imps = dir_imps,
303 cg_foreign = foreign_stubs,
304 cg_dep_pkgs = dep_pkgs deps,
305 cg_hpc_info = hpc_info,
306 cg_modBreaks = modBreaks },
308 ModDetails { md_types = tidy_type_env,
309 md_rules = tidy_rules,
310 md_insts = tidy_insts,
311 md_fam_insts = fam_insts,
312 md_exports = exports,
313 md_vect_info = vect_info -- is already tidy
317 lookup_dfun type_env dfun_id
318 = case lookupTypeEnv type_env (idName dfun_id) of
319 Just (AnId dfun_id') -> dfun_id'
320 other -> pprPanic "lookup_dfun" (ppr dfun_id)
322 tidyTypeEnv :: Bool -> NameSet -> TypeEnv -> [CoreBind] -> TypeEnv
324 -- The competed type environment is gotten from
325 -- Dropping any wired-in things, and then
326 -- a) keeping the types and classes
327 -- b) removing all Ids,
328 -- c) adding Ids with correct IdInfo, including unfoldings,
329 -- gotten from the bindings
330 -- From (c) we keep only those Ids with External names;
331 -- the CoreTidy pass makes sure these are all and only
332 -- the externally-accessible ones
333 -- This truncates the type environment to include only the
334 -- exported Ids and things needed from them, which saves space
336 tidyTypeEnv omit_prags exports type_env tidy_binds
337 = let type_env1 = filterNameEnv keep_it type_env
338 type_env2 = extendTypeEnvWithIds type_env1 final_ids
339 type_env3 | omit_prags = mapNameEnv trim_thing type_env2
340 | otherwise = type_env2
344 final_ids = [ id | id <- bindersOfBinds tidy_binds,
345 isExternalName (idName id)]
347 -- We keep GlobalIds, because they won't appear
348 -- in the bindings from which final_ids are derived!
349 -- (The bindings bind LocalIds.)
350 keep_it thing | isWiredInThing thing = False
351 keep_it (AnId id) = isGlobalId id -- Keep GlobalIds (e.g. class ops)
352 keep_it other = True -- Keep all TyCons, DataCons, and Classes
356 ATyCon tc | mustExposeTyCon exports tc -> thing
357 | otherwise -> ATyCon (makeTyConAbstract tc)
359 AnId id | isImplicitId id -> thing
360 | otherwise -> AnId (id `setIdInfo` vanillaIdInfo)
364 mustExposeTyCon :: NameSet -- Exports
365 -> TyCon -- The tycon
366 -> Bool -- Can its rep be hidden?
367 -- We are compiling without -O, and thus trying to write as little as
368 -- possible into the interface file. But we must expose the details of
369 -- any data types whose constructors or fields are exported
370 mustExposeTyCon exports tc
371 | not (isAlgTyCon tc) -- Synonyms
373 | isEnumerationTyCon tc -- For an enumeration, exposing the constructors
374 = True -- won't lead to the need for further exposure
375 -- (This includes data types with no constructors.)
376 | isOpenTyCon tc -- open type family
378 | otherwise -- Newtype, datatype
379 = any exported_con (tyConDataCons tc)
380 -- Expose rep if any datacon or field is exported
382 || (isNewTyCon tc && isFFITy (snd (newTyConRep tc)))
383 -- Expose the rep for newtypes if the rep is an FFI type.
384 -- For a very annoying reason. 'Foreign import' is meant to
385 -- be able to look through newtypes transparently, but it
386 -- can only do that if it can "see" the newtype representation
388 exported_con con = any (`elemNameSet` exports)
389 (dataConName con : dataConFieldLabels con)
391 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
392 tidyInstances tidy_dfun ispecs
395 tidy ispec = setInstanceDFunId ispec $
396 tidy_dfun (instanceDFunId ispec)
398 getImplicitBinds :: TypeEnv -> [CoreBind]
399 getImplicitBinds type_env
400 = map get_defn (concatMap implicit_con_ids (typeEnvTyCons type_env)
401 ++ concatMap other_implicit_ids (typeEnvElts type_env))
402 -- Put the constructor wrappers first, because
403 -- other implicit bindings (notably the fromT functions arising
404 -- from generics) use the constructor wrappers. At least that's
405 -- what External Core likes
407 implicit_con_ids tc = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
409 other_implicit_ids (ATyCon tc) = filter (not . isNaughtyRecordSelector) (tyConSelIds tc)
410 -- The "naughty" ones are not real functions at all
411 -- They are there just so we can get decent error messages
412 -- See Note [Naughty record selectors] in MkId.lhs
413 other_implicit_ids (AClass cl) = classSelIds cl
414 other_implicit_ids other = []
416 get_defn :: Id -> CoreBind
417 get_defn id = NonRec id (tidyExpr emptyTidyEnv rhs)
419 rhs = unfoldingTemplate (idUnfolding id)
420 -- Don't forget to tidy the body ! Otherwise you get silly things like
421 -- \ tpl -> case tpl of tpl -> (tpl,tpl) -> tpl
425 %************************************************************************
427 \subsection{Step 1: finding externals}
429 %************************************************************************
432 findExternalIds :: Bool
434 -> IdEnv Bool -- In domain => external
435 -- Range = True <=> show unfolding
436 -- Step 1 from the notes above
437 findExternalIds omit_prags binds
439 = mkVarEnv [ (id,False) | id <- bindersOfBinds binds, isExportedId id ]
442 = foldr find emptyVarEnv binds
444 find (NonRec id rhs) needed
445 | need_id needed id = addExternal (id,rhs) needed
447 find (Rec prs) needed = find_prs prs needed
449 -- For a recursive group we have to look for a fixed point
451 | null needed_prs = needed
452 | otherwise = find_prs other_prs new_needed
454 (needed_prs, other_prs) = partition (need_pr needed) prs
455 new_needed = foldr addExternal needed needed_prs
457 -- The 'needed' set contains the Ids that are needed by earlier
458 -- interface file emissions. If the Id isn't in this set, and isn't
459 -- exported, there's no need to emit anything
460 need_id needed_set id = id `elemVarEnv` needed_set || isExportedId id
461 need_pr needed_set (id,rhs) = need_id needed_set id
463 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
464 -- The Id is needed; extend the needed set
465 -- with it and its dependents (free vars etc)
466 addExternal (id,rhs) needed
467 = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
470 add_occ id needed | id `elemVarEnv` needed = needed
471 | otherwise = extendVarEnv needed id False
472 -- "False" because we don't know we need the Id's unfolding
473 -- Don't override existing bindings; we might have already set it to True
475 new_needed_ids = worker_ids `unionVarSet`
476 unfold_ids `unionVarSet`
480 dont_inline = isNeverActive (inlinePragInfo idinfo)
481 loop_breaker = isNonRuleLoopBreaker (occInfo idinfo)
482 bottoming_fn = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
483 spec_ids = specInfoFreeVars (specInfo idinfo)
484 worker_info = workerInfo idinfo
486 -- Stuff to do with the Id's unfolding
487 -- The simplifier has put an up-to-date unfolding
488 -- in the IdInfo, but the RHS will do just as well
489 unfolding = unfoldingInfo idinfo
490 rhs_is_small = not (neverUnfold unfolding)
492 -- We leave the unfolding there even if there is a worker
493 -- In GHCI the unfolding is used by importers
494 -- When writing an interface file, we omit the unfolding
495 -- if there is a worker
496 show_unfold = not bottoming_fn && -- Not necessary
499 rhs_is_small -- Small enough
501 unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
502 | otherwise = emptyVarSet
504 worker_ids = case worker_info of
505 HasWorker work_id _ -> unitVarSet work_id
506 otherwise -> emptyVarSet
511 findExternalRules :: [CoreBind]
512 -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
513 -> IdEnv a -- Ids that are exported, so we need their rules
515 -- The complete rules are gotten by combining
516 -- a) the non-local rules
517 -- b) rules embedded in the top-level Ids
518 findExternalRules binds non_local_rules ext_ids
519 = filter (not . internal_rule) (non_local_rules ++ local_rules)
522 | id <- bindersOfBinds binds,
523 id `elemVarEnv` ext_ids,
524 rule <- idCoreRules id
528 = any internal_id (varSetElems (ruleLhsFreeIds rule))
529 -- Don't export a rule whose LHS mentions a locally-defined
530 -- Id that is completely internal (i.e. not visible to an
533 internal_id id = not (id `elemVarEnv` ext_ids)
538 %************************************************************************
540 \subsection{Step 2: top-level tidying}
542 %************************************************************************
546 -- TopTidyEnv: when tidying we need to know
547 -- * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.
548 -- These may have arisen because the
549 -- renamer read in an interface file mentioning M.$wf, say,
550 -- and assigned it unique r77. If, on this compilation, we've
551 -- invented an Id whose name is $wf (but with a different unique)
552 -- we want to rename it to have unique r77, so that we can do easy
553 -- comparisons with stuff from the interface file
555 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
558 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
560 tidyTopBinds :: HscEnv
563 -> IdEnv Bool -- Domain = Ids that should be external
564 -- True <=> their unfolding is external too
566 -> IO (TidyEnv, [CoreBind])
568 tidyTopBinds hsc_env mod type_env ext_ids binds
569 = tidy init_env binds
571 nc_var = hsc_NC hsc_env
573 -- We also make sure to avoid any exported binders. Consider
574 -- f{-u1-} = 1 -- Local decl
576 -- f{-u2-} = 2 -- Exported decl
578 -- The second exported decl must 'get' the name 'f', so we
579 -- have to put 'f' in the avoids list before we get to the first
580 -- decl. tidyTopId then does a no-op on exported binders.
581 init_env = (initTidyOccEnv avoids, emptyVarEnv)
582 avoids = [getOccName name | bndr <- typeEnvIds type_env,
583 let name = idName bndr,
585 -- In computing our "avoids" list, we must include
587 -- all things with global names (assigned once and for
588 -- all by the renamer)
589 -- since their names are "taken".
590 -- The type environment is a convenient source of such things.
592 this_pkg = thisPackage (hsc_dflags hsc_env)
594 tidy env [] = return (env, [])
595 tidy env (b:bs) = do { (env1, b') <- tidyTopBind this_pkg mod nc_var ext_ids env b
596 ; (env2, bs') <- tidy env1 bs
597 ; return (env2, b':bs') }
599 ------------------------
600 tidyTopBind :: PackageId
602 -> IORef NameCache -- For allocating new unique names
603 -> IdEnv Bool -- Domain = Ids that should be external
604 -- True <=> their unfolding is external too
605 -> TidyEnv -> CoreBind
606 -> IO (TidyEnv, CoreBind)
608 tidyTopBind this_pkg mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (NonRec bndr rhs)
609 = do { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
610 ; let { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
611 ; subst2 = extendVarEnv subst1 bndr bndr'
612 ; tidy_env2 = (occ_env2, subst2) }
613 ; return (tidy_env2, NonRec bndr' rhs') }
615 caf_info = hasCafRefs this_pkg subst1 (idArity bndr) rhs
617 tidyTopBind this_pkg mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (Rec prs)
618 = do { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
619 ; let { prs' = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
621 ; subst2 = extendVarEnvList subst1 (bndrs `zip` map fst prs')
622 ; tidy_env2 = (occ_env2, subst2) }
623 ; return (tidy_env2, Rec prs') }
627 -- the CafInfo for a recursive group says whether *any* rhs in
628 -- the group may refer indirectly to a CAF (because then, they all do).
630 | or [ mayHaveCafRefs (hasCafRefs this_pkg subst1 (idArity bndr) rhs)
631 | (bndr,rhs) <- prs ] = MayHaveCafRefs
632 | otherwise = NoCafRefs
634 --------------------------------------------------------------------
636 -- This is where we set names to local/global based on whether they really are
637 -- externally visible (see comment at the top of this module). If the name
638 -- was previously local, we have to give it a unique occurrence name if
639 -- we intend to externalise it.
640 tidyTopNames mod nc_var ext_ids occ_env [] = return (occ_env, [])
641 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
642 = do { (occ_env1, name) <- tidyTopName mod nc_var ext_ids occ_env id
643 ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
644 ; return (occ_env2, name:names) }
646 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
647 -> Id -> IO (TidyOccEnv, Name)
648 tidyTopName mod nc_var ext_ids occ_env id
649 | global && internal = return (occ_env, localiseName name)
651 | global && external = return (occ_env, name)
652 -- Global names are assumed to have been allocated by the renamer,
653 -- so they already have the "right" unique
654 -- And it's a system-wide unique too
656 -- Now we get to the real reason that all this is in the IO Monad:
657 -- we have to update the name cache in a nice atomic fashion
659 | local && internal = do { nc <- readIORef nc_var
660 ; let (nc', new_local_name) = mk_new_local nc
661 ; writeIORef nc_var nc'
662 ; return (occ_env', new_local_name) }
663 -- Even local, internal names must get a unique occurrence, because
664 -- if we do -split-objs we externalise the name later, in the code generator
666 -- Similarly, we must make sure it has a system-wide Unique, because
667 -- the byte-code generator builds a system-wide Name->BCO symbol table
669 | local && external = do { nc <- readIORef nc_var
670 ; let (nc', new_external_name) = mk_new_external nc
671 ; writeIORef nc_var nc'
672 ; return (occ_env', new_external_name) }
675 external = id `elemVarEnv` ext_ids
676 global = isExternalName name
678 internal = not external
679 loc = nameSrcSpan name
681 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
683 mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
685 (us1, us2) = splitUniqSupply (nsUniqs nc)
686 uniq = uniqFromSupply us1
688 mk_new_external nc = allocateGlobalBinder nc mod occ' loc
689 -- If we want to externalise a currently-local name, check
690 -- whether we have already assigned a unique for it.
691 -- If so, use it; if not, extend the table.
692 -- All this is done by allcoateGlobalBinder.
693 -- This is needed when *re*-compiling a module in GHCi; we must
694 -- use the same name for externally-visible things as we did before.
697 -----------------------------------------------------------
698 tidyTopPair :: VarEnv Bool
699 -> TidyEnv -- The TidyEnv is used to tidy the IdInfo
700 -- It is knot-tied: don't look at it!
703 -> (Id, CoreExpr) -- Binder and RHS before tidying
705 -- This function is the heart of Step 2
706 -- The rec_tidy_env is the one to use for the IdInfo
707 -- It's necessary because when we are dealing with a recursive
708 -- group, a variable late in the group might be mentioned
709 -- in the IdInfo of one early in the group
711 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
712 | isGlobalId bndr -- Injected binding for record selector, etc
713 = (bndr, tidyExpr rhs_tidy_env rhs)
717 bndr' = mkVanillaGlobal name' ty' idinfo'
718 ty' = tidyTopType (idType bndr)
719 rhs' = tidyExpr rhs_tidy_env rhs
720 idinfo' = tidyTopIdInfo rhs_tidy_env (isJust maybe_external)
721 (idInfo bndr) unfold_info arity
724 -- Expose an unfolding if ext_ids tells us to
725 -- Remember that ext_ids maps an Id to a Bool:
726 -- True to show the unfolding, False to hide it
727 maybe_external = lookupVarEnv ext_ids bndr
728 show_unfold = maybe_external `orElse` False
729 unfold_info | show_unfold = mkTopUnfolding rhs'
730 | otherwise = noUnfolding
732 -- Usually the Id will have an accurate arity on it, because
733 -- the simplifier has just run, but not always.
734 -- One case I found was when the last thing the simplifier
735 -- did was to let-bind a non-atomic argument and then float
736 -- it to the top level. So it seems more robust just to
738 arity = exprArity rhs
741 -- tidyTopIdInfo creates the final IdInfo for top-level
742 -- binders. There are two delicate pieces:
744 -- * Arity. After CoreTidy, this arity must not change any more.
745 -- Indeed, CorePrep must eta expand where necessary to make
746 -- the manifest arity equal to the claimed arity.
748 -- * CAF info. This must also remain valid through to code generation.
749 -- We add the info here so that it propagates to all
750 -- occurrences of the binders in RHSs, and hence to occurrences in
751 -- unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
752 -- CoreToStg makes use of this when constructing SRTs.
754 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
755 | not is_external -- For internal Ids (not externally visible)
756 = vanillaIdInfo -- we only need enough info for code generation
757 -- Arity and strictness info are enough;
758 -- c.f. CoreTidy.tidyLetBndr
759 `setCafInfo` caf_info
761 `setAllStrictnessInfo` newStrictnessInfo idinfo
763 | otherwise -- Externally-visible Ids get the whole lot
765 `setCafInfo` caf_info
767 `setAllStrictnessInfo` newStrictnessInfo idinfo
768 `setInlinePragInfo` inlinePragInfo idinfo
769 `setUnfoldingInfo` unfold_info
770 `setWorkerInfo` tidyWorker tidy_env (workerInfo idinfo)
771 -- NB: we throw away the Rules
772 -- They have already been extracted by findExternalRules
776 ------------ Worker --------------
777 tidyWorker tidy_env (HasWorker work_id wrap_arity)
778 = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
779 tidyWorker tidy_env other
783 %************************************************************************
785 \subsection{Figuring out CafInfo for an expression}
787 %************************************************************************
789 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
790 We mark such things as `MayHaveCafRefs' because this information is
791 used to decide whether a particular closure needs to be referenced
794 There are two reasons for setting MayHaveCafRefs:
795 a) The RHS is a CAF: a top-level updatable thunk.
796 b) The RHS refers to something that MayHaveCafRefs
798 Possible improvement: In an effort to keep the number of CAFs (and
799 hence the size of the SRTs) down, we could also look at the expression and
800 decide whether it requires a small bounded amount of heap, so we can ignore
801 it as a CAF. In these cases however, we would need to use an additional
802 CAF list to keep track of non-collectable CAFs.
805 hasCafRefs :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
806 hasCafRefs this_pkg p arity expr
807 | is_caf || mentions_cafs
809 | otherwise = NoCafRefs
811 mentions_cafs = isFastTrue (cafRefs p expr)
812 is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
814 -- NB. we pass in the arity of the expression, which is expected
815 -- to be calculated by exprArity. This is because exprArity
816 -- knows how much eta expansion is going to be done by
817 -- CorePrep later on, and we don't want to duplicate that
818 -- knowledge in rhsIsStatic below.
821 -- imported Ids first:
822 | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
823 -- now Ids local to this module:
825 case lookupVarEnv p id of
826 Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
827 Nothing -> fastBool False
829 cafRefs p (Lit l) = fastBool False
830 cafRefs p (App f a) = fastOr (cafRefs p f) (cafRefs p) a
831 cafRefs p (Lam x e) = cafRefs p e
832 cafRefs p (Let b e) = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
833 cafRefs p (Case e bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
834 cafRefs p (Note n e) = cafRefs p e
835 cafRefs p (Cast e co) = cafRefs p e
836 cafRefs p (Type t) = fastBool False
838 cafRefss p [] = fastBool False
839 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
841 -- hack for lazy-or over FastBool.
842 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))