2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Tidying up Core}
7 module TidyPgm( mkBootModDetailsDs, mkBootModDetailsTc, tidyProgram ) where
9 #include "HsVersions.h"
23 import Var hiding( mkGlobalId )
43 import FastBool hiding ( fastOr )
45 import Data.List ( partition )
46 import Data.Maybe ( isJust )
47 import Data.IORef ( IORef, readIORef, writeIORef )
51 Constructing the TypeEnv, Instances, Rules from which the ModIface is
52 constructed, and which goes on to subsequent modules in --make mode.
54 Most of the interface file is obtained simply by serialising the
55 TypeEnv. One important consequence is that if the *interface file*
56 has pragma info if and only if the final TypeEnv does. This is not so
57 important for *this* module, but it's essential for ghc --make:
58 subsequent compilations must not see (e.g.) the arity if the interface
59 file does not contain arity If they do, they'll exploit the arity;
60 then the arity might change, but the iface file doesn't change =>
61 recompilation does not happen => disaster.
63 For data types, the final TypeEnv will have a TyThing for the TyCon,
64 plus one for each DataCon; the interface file will contain just one
65 data type declaration, but it is de-serialised back into a collection
68 %************************************************************************
72 %************************************************************************
75 Plan A: mkBootModDetails: omit pragmas, make interfaces small
76 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
79 * Drop all WiredIn things from the TypeEnv
80 (we never want them in interface files)
82 * Retain all TyCons and Classes in the TypeEnv, to avoid
83 having to find which ones are mentioned in the
86 * Trim off the constructors of non-exported TyCons, both
87 from the TyCon and from the TypeEnv
89 * Drop non-exported Ids from the TypeEnv
91 * Tidy the types of the DFunIds of Instances,
92 make them into GlobalIds, (they already have External Names)
93 and add them to the TypeEnv
95 * Tidy the types of the (exported) Ids in the TypeEnv,
96 make them into GlobalIds (they already have External Names)
98 * Drop rules altogether
100 * Tidy the bindings, to ensure that the Caf and Arity
101 information is correct for each top-level binder; the
102 code generator needs it. And to ensure that local names have
103 distinct OccNames in case of object-file splitting
106 -- This is Plan A: make a small type env when typechecking only,
107 -- or when compiling a hs-boot file, or simply when not using -O
109 -- We don't look at the bindings at all -- there aren't any
112 mkBootModDetailsTc :: HscEnv -> TcGblEnv -> IO ModDetails
113 mkBootModDetailsTc hsc_env
114 TcGblEnv{ tcg_exports = exports,
115 tcg_type_env = type_env,
117 tcg_fam_insts = fam_insts
119 = mkBootModDetails hsc_env exports type_env insts fam_insts
121 mkBootModDetailsDs :: HscEnv -> ModGuts -> IO ModDetails
122 mkBootModDetailsDs hsc_env
123 ModGuts{ mg_exports = exports,
126 mg_fam_insts = fam_insts
128 = mkBootModDetails hsc_env exports type_env insts fam_insts
130 mkBootModDetails :: HscEnv -> [AvailInfo] -> NameEnv TyThing
131 -> [Instance] -> [FamInstEnv.FamInst] -> IO ModDetails
132 mkBootModDetails hsc_env exports type_env insts fam_insts
133 = do { let dflags = hsc_dflags hsc_env
134 ; showPass dflags "Tidy [hoot] type env"
136 ; let { insts' = tidyInstances tidyExternalId insts
137 ; dfun_ids = map instanceDFunId insts'
138 ; type_env1 = tidyBootTypeEnv (availsToNameSet exports) type_env
139 ; type_env' = extendTypeEnvWithIds type_env1 dfun_ids
141 ; return (ModDetails { md_types = type_env'
143 , md_fam_insts = fam_insts
145 , md_exports = exports
146 , md_vect_info = noVectInfo
151 tidyBootTypeEnv :: NameSet -> TypeEnv -> TypeEnv
152 tidyBootTypeEnv exports type_env
153 = tidyTypeEnv True exports type_env final_ids
155 -- Find the LocalIds in the type env that are exported
156 -- Make them into GlobalIds, and tidy their types
158 -- It's very important to remove the non-exported ones
159 -- because we don't tidy the OccNames, and if we don't remove
160 -- the non-exported ones we'll get many things with the
161 -- same name in the interface file, giving chaos.
162 final_ids = [ tidyExternalId id
163 | id <- typeEnvIds type_env
167 -- default methods have their export flag set, but everything
168 -- else doesn't (yet), because this is pre-desugaring, so we
170 keep_it id = isExportedId id || idName id `elemNameSet` exports
173 tidyExternalId :: Id -> Id
174 -- Takes an LocalId with an External Name,
175 -- makes it into a GlobalId with VanillaIdInfo, and tidies its type
176 -- (NB: vanillaIdInfo makes a conservative assumption about Caf-hood.)
178 = ASSERT2( isLocalId id && isExternalName (idName id), ppr id )
179 mkVanillaGlobal (idName id) (tidyTopType (idType id)) vanillaIdInfo
183 %************************************************************************
185 Plan B: tidy bindings, make TypeEnv full of IdInfo
187 %************************************************************************
189 Plan B: include pragmas, make interfaces
190 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
191 * Figure out which Ids are externally visible
193 * Tidy the bindings, externalising appropriate Ids
195 * Drop all Ids from the TypeEnv, and add all the External Ids from
196 the bindings. (This adds their IdInfo to the TypeEnv; and adds
197 floated-out Ids that weren't even in the TypeEnv before.)
199 Step 1: Figure out external Ids
200 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
201 First we figure out which Ids are "external" Ids. An
202 "external" Id is one that is visible from outside the compilation
204 a) the user exported ones
205 b) ones mentioned in the unfoldings, workers,
206 or rules of externally-visible ones
207 This exercise takes a sweep of the bindings bottom to top. Actually,
208 in Step 2 we're also going to need to know which Ids should be
209 exported with their unfoldings, so we produce not an IdSet but an
213 Step 2: Tidy the program
214 ~~~~~~~~~~~~~~~~~~~~~~~~
215 Next we traverse the bindings top to bottom. For each *top-level*
218 1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal,
219 reflecting the fact that from now on we regard it as a global,
222 2. Give it a system-wide Unique.
223 [Even non-exported things need system-wide Uniques because the
224 byte-code generator builds a single Name->BCO symbol table.]
226 We use the NameCache kept in the HscEnv as the
227 source of such system-wide uniques.
229 For external Ids, use the original-name cache in the NameCache
230 to ensure that the unique assigned is the same as the Id had
231 in any previous compilation run.
233 3. If it's an external Id, make it have a External Name, otherwise
234 make it have an Internal Name.
235 This is used by the code generator to decide whether
236 to make the label externally visible
238 4. Give external Ids a "tidy" OccName. This means
239 we can print them in interface files without confusing
240 "x" (unique 5) with "x" (unique 10).
242 5. Give it its UTTERLY FINAL IdInfo; in ptic,
243 * its unfolding, if it should have one
245 * its arity, computed from the number of visible lambdas
247 * its CAF info, computed from what is free in its RHS
250 Finally, substitute these new top-level binders consistently
251 throughout, including in unfoldings. We also tidy binders in
252 RHSs, so that they print nicely in interfaces.
255 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
257 (ModGuts { mg_module = mod, mg_exports = exports,
259 mg_insts = insts, mg_fam_insts = fam_insts,
261 mg_rules = imp_rules,
262 mg_vect_info = vect_info,
263 mg_dir_imps = dir_imps,
265 mg_foreign = foreign_stubs,
266 mg_hpc_info = hpc_info,
267 mg_modBreaks = modBreaks })
269 = do { let dflags = hsc_dflags hsc_env
270 ; showPass dflags "Tidy Core"
272 ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
273 ; ext_ids = findExternalIds omit_prags binds
276 | otherwise = findExternalRules binds imp_rules ext_ids
277 -- findExternalRules filters imp_rules to avoid binders that
278 -- aren't externally visible; but the externally-visible binders
279 -- are computed (by findExternalIds) assuming that all orphan
280 -- rules are exported (they get their Exported flag set in the desugarer)
281 -- So in fact we may export more than we need.
282 -- (It's a sort of mutual recursion.)
285 ; (tidy_env, tidy_binds) <- tidyTopBinds hsc_env mod type_env ext_ids
288 ; let { export_set = availsToNameSet exports
289 ; final_ids = [ id | id <- bindersOfBinds tidy_binds,
290 isExternalName (idName id)]
291 ; tidy_type_env = tidyTypeEnv omit_prags export_set type_env
293 ; tidy_insts = tidyInstances (lookup_dfun tidy_type_env) insts
294 -- A DFunId will have a binding in tidy_binds, and so
295 -- will now be in final_env, replete with IdInfo
296 -- Its name will be unchanged since it was born, but
297 -- we want Global, IdInfo-rich (or not) DFunId in the
300 ; tidy_rules = tidyRules tidy_env ext_rules
301 -- You might worry that the tidy_env contains IdInfo-rich stuff
302 -- and indeed it does, but if omit_prags is on, ext_rules is
305 ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
308 ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
309 ; dumpIfSet_core dflags Opt_D_dump_simpl
311 (pprRules tidy_rules)
313 ; let dir_imp_mods = map fst (moduleEnvElts dir_imps)
315 ; return (CgGuts { cg_module = mod,
316 cg_tycons = alg_tycons,
317 cg_binds = tidy_binds,
318 cg_dir_imps = dir_imp_mods,
319 cg_foreign = foreign_stubs,
320 cg_dep_pkgs = dep_pkgs deps,
321 cg_hpc_info = hpc_info,
322 cg_modBreaks = modBreaks },
324 ModDetails { md_types = tidy_type_env,
325 md_rules = tidy_rules,
326 md_insts = tidy_insts,
327 md_fam_insts = fam_insts,
328 md_exports = exports,
329 md_vect_info = vect_info -- is already tidy
333 lookup_dfun :: TypeEnv -> Var -> Id
334 lookup_dfun type_env dfun_id
335 = case lookupTypeEnv type_env (idName dfun_id) of
336 Just (AnId dfun_id') -> dfun_id'
337 _other -> pprPanic "lookup_dfun" (ppr dfun_id)
339 --------------------------
340 tidyTypeEnv :: Bool -> NameSet -> TypeEnv -> [Id] -> TypeEnv
342 -- The competed type environment is gotten from
343 -- Dropping any wired-in things, and then
344 -- a) keeping the types and classes
345 -- b) removing all Ids,
346 -- c) adding Ids with correct IdInfo, including unfoldings,
347 -- gotten from the bindings
348 -- From (c) we keep only those Ids with External names;
349 -- the CoreTidy pass makes sure these are all and only
350 -- the externally-accessible ones
351 -- This truncates the type environment to include only the
352 -- exported Ids and things needed from them, which saves space
354 tidyTypeEnv omit_prags exports type_env final_ids
355 = let type_env1 = filterNameEnv keep_it type_env
356 type_env2 = extendTypeEnvWithIds type_env1 final_ids
357 type_env3 | omit_prags = mapNameEnv (trimThing exports) type_env2
358 | otherwise = type_env2
362 -- We keep GlobalIds, because they won't appear
363 -- in the bindings from which final_ids are derived!
364 -- (The bindings bind LocalIds.)
365 keep_it thing | isWiredInThing thing = False
366 keep_it (AnId id) = isGlobalId id -- Keep GlobalIds (e.g. class ops)
367 keep_it _other = True -- Keep all TyCons, DataCons, and Classes
369 --------------------------
370 isWiredInThing :: TyThing -> Bool
371 isWiredInThing thing = isWiredInName (getName thing)
373 --------------------------
374 trimThing :: NameSet -> TyThing -> TyThing
375 -- Trim off inessentials, for boot files and no -O
376 trimThing exports (ATyCon tc)
377 | not (mustExposeTyCon exports tc)
378 = ATyCon (makeTyConAbstract tc)
380 trimThing _exports (AnId id)
381 | not (isImplicitId id)
382 = AnId (id `setIdInfo` vanillaIdInfo)
384 trimThing _exports other_thing
388 mustExposeTyCon :: NameSet -- Exports
389 -> TyCon -- The tycon
390 -> Bool -- Can its rep be hidden?
391 -- We are compiling without -O, and thus trying to write as little as
392 -- possible into the interface file. But we must expose the details of
393 -- any data types whose constructors or fields are exported
394 mustExposeTyCon exports tc
395 | not (isAlgTyCon tc) -- Synonyms
397 | isEnumerationTyCon tc -- For an enumeration, exposing the constructors
398 = True -- won't lead to the need for further exposure
399 -- (This includes data types with no constructors.)
400 | isOpenTyCon tc -- Open type family
403 | otherwise -- Newtype, datatype
404 = any exported_con (tyConDataCons tc)
405 -- Expose rep if any datacon or field is exported
407 || (isNewTyCon tc && isFFITy (snd (newTyConRhs tc)))
408 -- Expose the rep for newtypes if the rep is an FFI type.
409 -- For a very annoying reason. 'Foreign import' is meant to
410 -- be able to look through newtypes transparently, but it
411 -- can only do that if it can "see" the newtype representation
413 exported_con con = any (`elemNameSet` exports)
414 (dataConName con : dataConFieldLabels con)
416 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
417 tidyInstances tidy_dfun ispecs
420 tidy ispec = setInstanceDFunId ispec $
421 tidy_dfun (instanceDFunId ispec)
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,_) = 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 (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 (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 :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
641 -> [Id] -> IO (TidyOccEnv, [Name])
642 tidyTopNames _mod _nc_var _ext_ids occ_env [] = return (occ_env, [])
643 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
644 = do { (occ_env1, name) <- tidyTopName mod nc_var ext_ids occ_env id
645 ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
646 ; return (occ_env2, name:names) }
648 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
649 -> Id -> IO (TidyOccEnv, Name)
650 tidyTopName mod nc_var ext_ids occ_env id
651 | global && internal = return (occ_env, localiseName name)
653 | global && external = return (occ_env, name)
654 -- Global names are assumed to have been allocated by the renamer,
655 -- so they already have the "right" unique
656 -- And it's a system-wide unique too
658 -- Now we get to the real reason that all this is in the IO Monad:
659 -- we have to update the name cache in a nice atomic fashion
661 | local && internal = do { nc <- readIORef nc_var
662 ; let (nc', new_local_name) = mk_new_local nc
663 ; writeIORef nc_var nc'
664 ; return (occ_env', new_local_name) }
665 -- Even local, internal names must get a unique occurrence, because
666 -- if we do -split-objs we externalise the name later, in the code generator
668 -- Similarly, we must make sure it has a system-wide Unique, because
669 -- the byte-code generator builds a system-wide Name->BCO symbol table
671 | local && external = do { nc <- readIORef nc_var
672 ; let (nc', new_external_name) = mk_new_external nc
673 ; writeIORef nc_var nc'
674 ; return (occ_env', new_external_name) }
676 | otherwise = panic "tidyTopName"
679 external = id `elemVarEnv` ext_ids
680 global = isExternalName name
682 internal = not external
683 loc = nameSrcSpan name
685 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
687 mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
689 (us1, us2) = splitUniqSupply (nsUniqs nc)
690 uniq = uniqFromSupply us1
692 mk_new_external nc = allocateGlobalBinder nc mod occ' loc
693 -- If we want to externalise a currently-local name, check
694 -- whether we have already assigned a unique for it.
695 -- If so, use it; if not, extend the table.
696 -- All this is done by allcoateGlobalBinder.
697 -- This is needed when *re*-compiling a module in GHCi; we must
698 -- use the same name for externally-visible things as we did before.
701 -----------------------------------------------------------
702 tidyTopPair :: VarEnv Bool
703 -> TidyEnv -- The TidyEnv is used to tidy the IdInfo
704 -- It is knot-tied: don't look at it!
707 -> (Id, CoreExpr) -- Binder and RHS before tidying
709 -- This function is the heart of Step 2
710 -- The rec_tidy_env is the one to use for the IdInfo
711 -- It's necessary because when we are dealing with a recursive
712 -- group, a variable late in the group might be mentioned
713 -- in the IdInfo of one early in the group
715 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
718 bndr' = mkGlobalId details name' ty' idinfo'
719 -- Preserve the GlobalIdDetails of existing global-ids
720 details = case globalIdDetails bndr of
721 NotGlobalId -> VanillaGlobal
722 old_details -> old_details
723 ty' = tidyTopType (idType bndr)
724 rhs' = tidyExpr rhs_tidy_env rhs
726 idinfo' = tidyTopIdInfo (isJust maybe_external)
727 idinfo unfold_info worker_info
730 -- Expose an unfolding if ext_ids tells us to
731 -- Remember that ext_ids maps an Id to a Bool:
732 -- True to show the unfolding, False to hide it
733 maybe_external = lookupVarEnv ext_ids bndr
734 show_unfold = maybe_external `orElse` False
735 unfold_info | show_unfold = mkTopUnfolding rhs'
736 | otherwise = noUnfolding
737 worker_info = tidyWorker rhs_tidy_env show_unfold (workerInfo idinfo)
739 -- Usually the Id will have an accurate arity on it, because
740 -- the simplifier has just run, but not always.
741 -- One case I found was when the last thing the simplifier
742 -- did was to let-bind a non-atomic argument and then float
743 -- it to the top level. So it seems more robust just to
745 arity = exprArity rhs
748 -- tidyTopIdInfo creates the final IdInfo for top-level
749 -- binders. There are two delicate pieces:
751 -- * Arity. After CoreTidy, this arity must not change any more.
752 -- Indeed, CorePrep must eta expand where necessary to make
753 -- the manifest arity equal to the claimed arity.
755 -- * CAF info. This must also remain valid through to code generation.
756 -- We add the info here so that it propagates to all
757 -- occurrences of the binders in RHSs, and hence to occurrences in
758 -- unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
759 -- CoreToStg makes use of this when constructing SRTs.
760 tidyTopIdInfo :: Bool -> IdInfo -> Unfolding
761 -> WorkerInfo -> ArityInfo -> CafInfo
763 tidyTopIdInfo is_external idinfo unfold_info worker_info arity caf_info
764 | not is_external -- For internal Ids (not externally visible)
765 = vanillaIdInfo -- we only need enough info for code generation
766 -- Arity and strictness info are enough;
767 -- c.f. CoreTidy.tidyLetBndr
768 `setCafInfo` caf_info
770 `setAllStrictnessInfo` newStrictnessInfo idinfo
772 | otherwise -- Externally-visible Ids get the whole lot
774 `setCafInfo` caf_info
776 `setAllStrictnessInfo` newStrictnessInfo idinfo
777 `setInlinePragInfo` inlinePragInfo idinfo
778 `setUnfoldingInfo` unfold_info
779 `setWorkerInfo` worker_info
780 -- NB: we throw away the Rules
781 -- They have already been extracted by findExternalRules
785 ------------ Worker --------------
786 tidyWorker :: TidyEnv -> Bool -> WorkerInfo -> WorkerInfo
787 tidyWorker _tidy_env _show_unfold NoWorker
789 tidyWorker tidy_env show_unfold (HasWorker work_id wrap_arity)
790 | show_unfold = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
791 | otherwise = NoWorker
792 -- NB: do *not* expose the worker if show_unfold is off,
793 -- because that means this thing is a loop breaker or
794 -- marked NOINLINE or something like that
795 -- This is important: if you expose the worker for a loop-breaker
796 -- then you can make the simplifier go into an infinite loop, because
797 -- in effect the unfolding is exposed. See Trac #1709
799 -- You might think that if show_unfold is False, then the thing should
800 -- not be w/w'd in the first place. But a legitimate reason is this:
801 -- the function returns bottom
802 -- In this case, show_unfold will be false (we don't expose unfoldings
803 -- for bottoming functions), but we might still have a worker/wrapper
804 -- split (see Note [Worker-wrapper for bottoming functions] in WorkWrap.lhs
807 %************************************************************************
809 \subsection{Figuring out CafInfo for an expression}
811 %************************************************************************
813 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
814 We mark such things as `MayHaveCafRefs' because this information is
815 used to decide whether a particular closure needs to be referenced
818 There are two reasons for setting MayHaveCafRefs:
819 a) The RHS is a CAF: a top-level updatable thunk.
820 b) The RHS refers to something that MayHaveCafRefs
822 Possible improvement: In an effort to keep the number of CAFs (and
823 hence the size of the SRTs) down, we could also look at the expression and
824 decide whether it requires a small bounded amount of heap, so we can ignore
825 it as a CAF. In these cases however, we would need to use an additional
826 CAF list to keep track of non-collectable CAFs.
829 hasCafRefs :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
830 hasCafRefs this_pkg p arity expr
831 | is_caf || mentions_cafs
833 | otherwise = NoCafRefs
835 mentions_cafs = isFastTrue (cafRefs p expr)
836 is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
838 -- NB. we pass in the arity of the expression, which is expected
839 -- to be calculated by exprArity. This is because exprArity
840 -- knows how much eta expansion is going to be done by
841 -- CorePrep later on, and we don't want to duplicate that
842 -- knowledge in rhsIsStatic below.
844 cafRefs :: VarEnv Id -> Expr a -> FastBool
846 -- imported Ids first:
847 | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
848 -- now Ids local to this module:
850 case lookupVarEnv p id of
851 Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
852 Nothing -> fastBool False
854 cafRefs _ (Lit _) = fastBool False
855 cafRefs p (App f a) = fastOr (cafRefs p f) (cafRefs p) a
856 cafRefs p (Lam _ e) = cafRefs p e
857 cafRefs p (Let b e) = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
858 cafRefs p (Case e _bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
859 cafRefs p (Note _n e) = cafRefs p e
860 cafRefs p (Cast e _co) = cafRefs p e
861 cafRefs _ (Type _) = fastBool False
863 cafRefss :: VarEnv Id -> [Expr a] -> FastBool
864 cafRefss _ [] = fastBool False
865 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
867 fastOr :: FastBool -> (a -> FastBool) -> a -> FastBool
868 -- hack for lazy-or over FastBool.
869 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))