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"
44 import FastTypes hiding (fastOr)
46 import Data.List ( partition )
47 import Data.Maybe ( isJust )
48 import Data.IORef ( IORef, readIORef, writeIORef )
50 _dummy :: FS.FastString
55 Constructing the TypeEnv, Instances, Rules from which the ModIface is
56 constructed, and which goes on to subsequent modules in --make mode.
58 Most of the interface file is obtained simply by serialising the
59 TypeEnv. One important consequence is that if the *interface file*
60 has pragma info if and only if the final TypeEnv does. This is not so
61 important for *this* module, but it's essential for ghc --make:
62 subsequent compilations must not see (e.g.) the arity if the interface
63 file does not contain arity If they do, they'll exploit the arity;
64 then the arity might change, but the iface file doesn't change =>
65 recompilation does not happen => disaster.
67 For data types, the final TypeEnv will have a TyThing for the TyCon,
68 plus one for each DataCon; the interface file will contain just one
69 data type declaration, but it is de-serialised back into a collection
72 %************************************************************************
76 %************************************************************************
79 Plan A: mkBootModDetails: omit pragmas, make interfaces small
80 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
83 * Drop all WiredIn things from the TypeEnv
84 (we never want them in interface files)
86 * Retain all TyCons and Classes in the TypeEnv, to avoid
87 having to find which ones are mentioned in the
90 * Trim off the constructors of non-exported TyCons, both
91 from the TyCon and from the TypeEnv
93 * Drop non-exported Ids from the TypeEnv
95 * Tidy the types of the DFunIds of Instances,
96 make them into GlobalIds, (they already have External Names)
97 and add them to the TypeEnv
99 * Tidy the types of the (exported) Ids in the TypeEnv,
100 make them into GlobalIds (they already have External Names)
102 * Drop rules altogether
104 * Tidy the bindings, to ensure that the Caf and Arity
105 information is correct for each top-level binder; the
106 code generator needs it. And to ensure that local names have
107 distinct OccNames in case of object-file splitting
110 -- This is Plan A: make a small type env when typechecking only,
111 -- or when compiling a hs-boot file, or simply when not using -O
113 -- We don't look at the bindings at all -- there aren't any
116 mkBootModDetailsTc :: HscEnv -> TcGblEnv -> IO ModDetails
117 mkBootModDetailsTc hsc_env
118 TcGblEnv{ tcg_exports = exports,
119 tcg_type_env = type_env,
121 tcg_fam_insts = fam_insts
123 = mkBootModDetails hsc_env exports type_env insts fam_insts
125 mkBootModDetailsDs :: HscEnv -> ModGuts -> IO ModDetails
126 mkBootModDetailsDs hsc_env
127 ModGuts{ mg_exports = exports,
130 mg_fam_insts = fam_insts
132 = mkBootModDetails hsc_env exports type_env insts fam_insts
134 mkBootModDetails :: HscEnv -> [AvailInfo] -> NameEnv TyThing
135 -> [Instance] -> [FamInstEnv.FamInst] -> IO ModDetails
136 mkBootModDetails hsc_env exports type_env insts fam_insts
137 = do { let dflags = hsc_dflags hsc_env
138 ; showPass dflags "Tidy [hoot] type env"
140 ; let { insts' = tidyInstances tidyExternalId insts
141 ; dfun_ids = map instanceDFunId insts'
142 ; type_env1 = tidyBootTypeEnv (availsToNameSet exports) type_env
143 ; type_env' = extendTypeEnvWithIds type_env1 dfun_ids
145 ; return (ModDetails { md_types = type_env'
147 , md_fam_insts = fam_insts
149 , md_exports = exports
150 , md_vect_info = noVectInfo
155 tidyBootTypeEnv :: NameSet -> TypeEnv -> TypeEnv
156 tidyBootTypeEnv exports type_env
157 = tidyTypeEnv True exports type_env final_ids
159 -- Find the LocalIds in the type env that are exported
160 -- Make them into GlobalIds, and tidy their types
162 -- It's very important to remove the non-exported ones
163 -- because we don't tidy the OccNames, and if we don't remove
164 -- the non-exported ones we'll get many things with the
165 -- same name in the interface file, giving chaos.
166 final_ids = [ tidyExternalId id
167 | id <- typeEnvIds type_env
171 -- default methods have their export flag set, but everything
172 -- else doesn't (yet), because this is pre-desugaring, so we
174 keep_it id = isExportedId id || idName id `elemNameSet` exports
177 tidyExternalId :: Id -> Id
178 -- Takes an LocalId with an External Name,
179 -- makes it into a GlobalId with VanillaIdInfo, and tidies its type
180 -- (NB: vanillaIdInfo makes a conservative assumption about Caf-hood.)
182 = ASSERT2( isLocalId id && isExternalName (idName id), ppr id )
183 mkVanillaGlobal (idName id) (tidyTopType (idType id)) vanillaIdInfo
187 %************************************************************************
189 Plan B: tidy bindings, make TypeEnv full of IdInfo
191 %************************************************************************
193 Plan B: include pragmas, make interfaces
194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
195 * Figure out which Ids are externally visible
197 * Tidy the bindings, externalising appropriate Ids
199 * Drop all Ids from the TypeEnv, and add all the External Ids from
200 the bindings. (This adds their IdInfo to the TypeEnv; and adds
201 floated-out Ids that weren't even in the TypeEnv before.)
203 Step 1: Figure out external Ids
204 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
205 First we figure out which Ids are "external" Ids. An
206 "external" Id is one that is visible from outside the compilation
208 a) the user exported ones
209 b) ones mentioned in the unfoldings, workers,
210 or rules of externally-visible ones
211 This exercise takes a sweep of the bindings bottom to top. Actually,
212 in Step 2 we're also going to need to know which Ids should be
213 exported with their unfoldings, so we produce not an IdSet but an
217 Step 2: Tidy the program
218 ~~~~~~~~~~~~~~~~~~~~~~~~
219 Next we traverse the bindings top to bottom. For each *top-level*
222 1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal,
223 reflecting the fact that from now on we regard it as a global,
226 2. Give it a system-wide Unique.
227 [Even non-exported things need system-wide Uniques because the
228 byte-code generator builds a single Name->BCO symbol table.]
230 We use the NameCache kept in the HscEnv as the
231 source of such system-wide uniques.
233 For external Ids, use the original-name cache in the NameCache
234 to ensure that the unique assigned is the same as the Id had
235 in any previous compilation run.
237 3. If it's an external Id, make it have a External Name, otherwise
238 make it have an Internal Name.
239 This is used by the code generator to decide whether
240 to make the label externally visible
242 4. Give external Ids a "tidy" OccName. This means
243 we can print them in interface files without confusing
244 "x" (unique 5) with "x" (unique 10).
246 5. Give it its UTTERLY FINAL IdInfo; in ptic,
247 * its unfolding, if it should have one
249 * its arity, computed from the number of visible lambdas
251 * its CAF info, computed from what is free in its RHS
254 Finally, substitute these new top-level binders consistently
255 throughout, including in unfoldings. We also tidy binders in
256 RHSs, so that they print nicely in interfaces.
259 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
261 (ModGuts { mg_module = mod, mg_exports = exports,
263 mg_insts = insts, mg_fam_insts = fam_insts,
265 mg_rules = imp_rules,
266 mg_vect_info = vect_info,
267 mg_dir_imps = dir_imps,
269 mg_foreign = foreign_stubs,
270 mg_hpc_info = hpc_info,
271 mg_modBreaks = modBreaks })
273 = do { let dflags = hsc_dflags hsc_env
274 ; showPass dflags "Tidy Core"
276 ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
277 ; ext_ids = findExternalIds omit_prags binds
280 | otherwise = findExternalRules binds imp_rules ext_ids
281 -- findExternalRules filters imp_rules to avoid binders that
282 -- aren't externally visible; but the externally-visible binders
283 -- are computed (by findExternalIds) assuming that all orphan
284 -- rules are exported (they get their Exported flag set in the desugarer)
285 -- So in fact we may export more than we need.
286 -- (It's a sort of mutual recursion.)
289 ; (tidy_env, tidy_binds) <- tidyTopBinds hsc_env mod type_env ext_ids
292 ; let { export_set = availsToNameSet exports
293 ; final_ids = [ id | id <- bindersOfBinds tidy_binds,
294 isExternalName (idName id)]
295 ; tidy_type_env = tidyTypeEnv omit_prags export_set type_env
297 ; tidy_insts = tidyInstances (lookup_dfun tidy_type_env) insts
298 -- A DFunId will have a binding in tidy_binds, and so
299 -- will now be in final_env, replete with IdInfo
300 -- Its name will be unchanged since it was born, but
301 -- we want Global, IdInfo-rich (or not) DFunId in the
304 ; tidy_rules = tidyRules tidy_env ext_rules
305 -- You might worry that the tidy_env contains IdInfo-rich stuff
306 -- and indeed it does, but if omit_prags is on, ext_rules is
309 ; implicit_binds = getImplicitBinds type_env
310 ; all_tidy_binds = implicit_binds ++ tidy_binds
311 ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
314 ; endPass dflags "Tidy Core" Opt_D_dump_simpl all_tidy_binds
315 ; dumpIfSet_core dflags Opt_D_dump_simpl
317 (pprRules tidy_rules)
319 ; let dir_imp_mods = map fst (moduleEnvElts dir_imps)
321 ; return (CgGuts { cg_module = mod,
322 cg_tycons = alg_tycons,
323 cg_binds = all_tidy_binds,
324 cg_dir_imps = dir_imp_mods,
325 cg_foreign = foreign_stubs,
326 cg_dep_pkgs = dep_pkgs deps,
327 cg_hpc_info = hpc_info,
328 cg_modBreaks = modBreaks },
330 ModDetails { md_types = tidy_type_env,
331 md_rules = tidy_rules,
332 md_insts = tidy_insts,
333 md_fam_insts = fam_insts,
334 md_exports = exports,
335 md_vect_info = vect_info -- is already tidy
339 lookup_dfun :: TypeEnv -> Var -> Id
340 lookup_dfun type_env dfun_id
341 = case lookupTypeEnv type_env (idName dfun_id) of
342 Just (AnId dfun_id') -> dfun_id'
343 _other -> pprPanic "lookup_dfun" (ppr dfun_id)
345 --------------------------
346 tidyTypeEnv :: Bool -> NameSet -> TypeEnv -> [Id] -> TypeEnv
348 -- The competed type environment is gotten from
349 -- Dropping any wired-in things, and then
350 -- a) keeping the types and classes
351 -- b) removing all Ids,
352 -- c) adding Ids with correct IdInfo, including unfoldings,
353 -- gotten from the bindings
354 -- From (c) we keep only those Ids with External names;
355 -- the CoreTidy pass makes sure these are all and only
356 -- the externally-accessible ones
357 -- This truncates the type environment to include only the
358 -- exported Ids and things needed from them, which saves space
360 tidyTypeEnv omit_prags exports type_env final_ids
361 = let type_env1 = filterNameEnv keep_it type_env
362 type_env2 = extendTypeEnvWithIds type_env1 final_ids
363 type_env3 | omit_prags = mapNameEnv (trimThing exports) type_env2
364 | otherwise = type_env2
368 -- We keep GlobalIds, because they won't appear
369 -- in the bindings from which final_ids are derived!
370 -- (The bindings bind LocalIds.)
371 keep_it thing | isWiredInThing thing = False
372 keep_it (AnId id) = isGlobalId id -- Keep GlobalIds (e.g. class ops)
373 keep_it _other = True -- Keep all TyCons, DataCons, and Classes
375 --------------------------
376 isWiredInThing :: TyThing -> Bool
377 isWiredInThing thing = isWiredInName (getName thing)
379 --------------------------
380 trimThing :: NameSet -> TyThing -> TyThing
381 -- Trim off inessentials, for boot files and no -O
382 trimThing exports (ATyCon tc)
383 | not (mustExposeTyCon exports tc)
384 = ATyCon (makeTyConAbstract tc)
386 trimThing _exports (AnId id)
387 | not (isImplicitId id)
388 = AnId (id `setIdInfo` vanillaIdInfo)
390 trimThing _exports other_thing
394 mustExposeTyCon :: NameSet -- Exports
395 -> TyCon -- The tycon
396 -> Bool -- Can its rep be hidden?
397 -- We are compiling without -O, and thus trying to write as little as
398 -- possible into the interface file. But we must expose the details of
399 -- any data types whose constructors or fields are exported
400 mustExposeTyCon exports tc
401 | not (isAlgTyCon tc) -- Synonyms
403 | isEnumerationTyCon tc -- For an enumeration, exposing the constructors
404 = True -- won't lead to the need for further exposure
405 -- (This includes data types with no constructors.)
406 | isOpenTyCon tc -- open type family
408 | otherwise -- Newtype, datatype
409 = any exported_con (tyConDataCons tc)
410 -- Expose rep if any datacon or field is exported
412 || (isNewTyCon tc && isFFITy (snd (newTyConRep tc)))
413 -- Expose the rep for newtypes if the rep is an FFI type.
414 -- For a very annoying reason. 'Foreign import' is meant to
415 -- be able to look through newtypes transparently, but it
416 -- can only do that if it can "see" the newtype representation
418 exported_con con = any (`elemNameSet` exports)
419 (dataConName con : dataConFieldLabels con)
421 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
422 tidyInstances tidy_dfun ispecs
425 tidy ispec = setInstanceDFunId ispec $
426 tidy_dfun (instanceDFunId ispec)
428 getImplicitBinds :: TypeEnv -> [CoreBind]
429 getImplicitBinds type_env
430 = map get_defn (concatMap implicit_con_ids (typeEnvTyCons type_env)
431 ++ concatMap other_implicit_ids (typeEnvElts type_env))
432 -- Put the constructor wrappers first, because
433 -- other implicit bindings (notably the fromT functions arising
434 -- from generics) use the constructor wrappers. At least that's
435 -- what External Core likes
437 implicit_con_ids tc = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
439 other_implicit_ids (ATyCon tc) = filter (not . isNaughtyRecordSelector) (tyConSelIds tc)
440 -- The "naughty" ones are not real functions at all
441 -- They are there just so we can get decent error messages
442 -- See Note [Naughty record selectors] in MkId.lhs
443 other_implicit_ids (AClass cl) = classSelIds cl
444 other_implicit_ids _other = []
446 get_defn :: Id -> CoreBind
447 get_defn id = NonRec id (tidyExpr emptyTidyEnv rhs)
449 rhs = unfoldingTemplate (idUnfolding id)
450 -- Don't forget to tidy the body ! Otherwise you get silly things like
451 -- \ tpl -> case tpl of tpl -> (tpl,tpl) -> tpl
455 %************************************************************************
457 \subsection{Step 1: finding externals}
459 %************************************************************************
462 findExternalIds :: Bool
464 -> IdEnv Bool -- In domain => external
465 -- Range = True <=> show unfolding
466 -- Step 1 from the notes above
467 findExternalIds omit_prags binds
469 = mkVarEnv [ (id,False) | id <- bindersOfBinds binds, isExportedId id ]
472 = foldr find emptyVarEnv binds
474 find (NonRec id rhs) needed
475 | need_id needed id = addExternal (id,rhs) needed
477 find (Rec prs) needed = find_prs prs needed
479 -- For a recursive group we have to look for a fixed point
481 | null needed_prs = needed
482 | otherwise = find_prs other_prs new_needed
484 (needed_prs, other_prs) = partition (need_pr needed) prs
485 new_needed = foldr addExternal needed needed_prs
487 -- The 'needed' set contains the Ids that are needed by earlier
488 -- interface file emissions. If the Id isn't in this set, and isn't
489 -- exported, there's no need to emit anything
490 need_id needed_set id = id `elemVarEnv` needed_set || isExportedId id
491 need_pr needed_set (id,_) = need_id needed_set id
493 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
494 -- The Id is needed; extend the needed set
495 -- with it and its dependents (free vars etc)
496 addExternal (id,rhs) needed
497 = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
500 add_occ id needed | id `elemVarEnv` needed = needed
501 | otherwise = extendVarEnv needed id False
502 -- "False" because we don't know we need the Id's unfolding
503 -- Don't override existing bindings; we might have already set it to True
505 new_needed_ids = worker_ids `unionVarSet`
506 unfold_ids `unionVarSet`
510 dont_inline = isNeverActive (inlinePragInfo idinfo)
511 loop_breaker = isNonRuleLoopBreaker (occInfo idinfo)
512 bottoming_fn = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
513 spec_ids = specInfoFreeVars (specInfo idinfo)
514 worker_info = workerInfo idinfo
516 -- Stuff to do with the Id's unfolding
517 -- The simplifier has put an up-to-date unfolding
518 -- in the IdInfo, but the RHS will do just as well
519 unfolding = unfoldingInfo idinfo
520 rhs_is_small = not (neverUnfold unfolding)
522 -- We leave the unfolding there even if there is a worker
523 -- In GHCI the unfolding is used by importers
524 -- When writing an interface file, we omit the unfolding
525 -- if there is a worker
526 show_unfold = not bottoming_fn && -- Not necessary
529 rhs_is_small -- Small enough
531 unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
532 | otherwise = emptyVarSet
534 worker_ids = case worker_info of
535 HasWorker work_id _ -> unitVarSet work_id
536 _otherwise -> emptyVarSet
541 findExternalRules :: [CoreBind]
542 -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
543 -> IdEnv a -- Ids that are exported, so we need their rules
545 -- The complete rules are gotten by combining
546 -- a) the non-local rules
547 -- b) rules embedded in the top-level Ids
548 findExternalRules binds non_local_rules ext_ids
549 = filter (not . internal_rule) (non_local_rules ++ local_rules)
552 | id <- bindersOfBinds binds,
553 id `elemVarEnv` ext_ids,
554 rule <- idCoreRules id
558 = any internal_id (varSetElems (ruleLhsFreeIds rule))
559 -- Don't export a rule whose LHS mentions a locally-defined
560 -- Id that is completely internal (i.e. not visible to an
563 internal_id id = not (id `elemVarEnv` ext_ids)
568 %************************************************************************
570 \subsection{Step 2: top-level tidying}
572 %************************************************************************
576 -- TopTidyEnv: when tidying we need to know
577 -- * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.
578 -- These may have arisen because the
579 -- renamer read in an interface file mentioning M.$wf, say,
580 -- and assigned it unique r77. If, on this compilation, we've
581 -- invented an Id whose name is $wf (but with a different unique)
582 -- we want to rename it to have unique r77, so that we can do easy
583 -- comparisons with stuff from the interface file
585 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
588 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
590 tidyTopBinds :: HscEnv
593 -> IdEnv Bool -- Domain = Ids that should be external
594 -- True <=> their unfolding is external too
596 -> IO (TidyEnv, [CoreBind])
598 tidyTopBinds hsc_env mod type_env ext_ids binds
599 = tidy init_env binds
601 nc_var = hsc_NC hsc_env
603 -- We also make sure to avoid any exported binders. Consider
604 -- f{-u1-} = 1 -- Local decl
606 -- f{-u2-} = 2 -- Exported decl
608 -- The second exported decl must 'get' the name 'f', so we
609 -- have to put 'f' in the avoids list before we get to the first
610 -- decl. tidyTopId then does a no-op on exported binders.
611 init_env = (initTidyOccEnv avoids, emptyVarEnv)
612 avoids = [getOccName name | bndr <- typeEnvIds type_env,
613 let name = idName bndr,
615 -- In computing our "avoids" list, we must include
617 -- all things with global names (assigned once and for
618 -- all by the renamer)
619 -- since their names are "taken".
620 -- The type environment is a convenient source of such things.
622 this_pkg = thisPackage (hsc_dflags hsc_env)
624 tidy env [] = return (env, [])
625 tidy env (b:bs) = do { (env1, b') <- tidyTopBind this_pkg mod nc_var ext_ids env b
626 ; (env2, bs') <- tidy env1 bs
627 ; return (env2, b':bs') }
629 ------------------------
630 tidyTopBind :: PackageId
632 -> IORef NameCache -- For allocating new unique names
633 -> IdEnv Bool -- Domain = Ids that should be external
634 -- True <=> their unfolding is external too
635 -> TidyEnv -> CoreBind
636 -> IO (TidyEnv, CoreBind)
638 tidyTopBind this_pkg mod nc_var ext_ids (occ_env1,subst1) (NonRec bndr rhs)
639 = do { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
640 ; let { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
641 ; subst2 = extendVarEnv subst1 bndr bndr'
642 ; tidy_env2 = (occ_env2, subst2) }
643 ; return (tidy_env2, NonRec bndr' rhs') }
645 caf_info = hasCafRefs this_pkg subst1 (idArity bndr) rhs
647 tidyTopBind this_pkg mod nc_var ext_ids (occ_env1,subst1) (Rec prs)
648 = do { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
649 ; let { prs' = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
651 ; subst2 = extendVarEnvList subst1 (bndrs `zip` map fst prs')
652 ; tidy_env2 = (occ_env2, subst2) }
653 ; return (tidy_env2, Rec prs') }
657 -- the CafInfo for a recursive group says whether *any* rhs in
658 -- the group may refer indirectly to a CAF (because then, they all do).
660 | or [ mayHaveCafRefs (hasCafRefs this_pkg subst1 (idArity bndr) rhs)
661 | (bndr,rhs) <- prs ] = MayHaveCafRefs
662 | otherwise = NoCafRefs
664 --------------------------------------------------------------------
666 -- This is where we set names to local/global based on whether they really are
667 -- externally visible (see comment at the top of this module). If the name
668 -- was previously local, we have to give it a unique occurrence name if
669 -- we intend to externalise it.
670 tidyTopNames :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
671 -> [Id] -> IO (TidyOccEnv, [Name])
672 tidyTopNames _mod _nc_var _ext_ids occ_env [] = return (occ_env, [])
673 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
674 = do { (occ_env1, name) <- tidyTopName mod nc_var ext_ids occ_env id
675 ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
676 ; return (occ_env2, name:names) }
678 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
679 -> Id -> IO (TidyOccEnv, Name)
680 tidyTopName mod nc_var ext_ids occ_env id
681 | global && internal = return (occ_env, localiseName name)
683 | global && external = return (occ_env, name)
684 -- Global names are assumed to have been allocated by the renamer,
685 -- so they already have the "right" unique
686 -- And it's a system-wide unique too
688 -- Now we get to the real reason that all this is in the IO Monad:
689 -- we have to update the name cache in a nice atomic fashion
691 | local && internal = do { nc <- readIORef nc_var
692 ; let (nc', new_local_name) = mk_new_local nc
693 ; writeIORef nc_var nc'
694 ; return (occ_env', new_local_name) }
695 -- Even local, internal names must get a unique occurrence, because
696 -- if we do -split-objs we externalise the name later, in the code generator
698 -- Similarly, we must make sure it has a system-wide Unique, because
699 -- the byte-code generator builds a system-wide Name->BCO symbol table
701 | local && external = do { nc <- readIORef nc_var
702 ; let (nc', new_external_name) = mk_new_external nc
703 ; writeIORef nc_var nc'
704 ; return (occ_env', new_external_name) }
706 | otherwise = panic "tidyTopName"
709 external = id `elemVarEnv` ext_ids
710 global = isExternalName name
712 internal = not external
713 loc = nameSrcSpan name
715 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
717 mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
719 (us1, us2) = splitUniqSupply (nsUniqs nc)
720 uniq = uniqFromSupply us1
722 mk_new_external nc = allocateGlobalBinder nc mod occ' loc
723 -- If we want to externalise a currently-local name, check
724 -- whether we have already assigned a unique for it.
725 -- If so, use it; if not, extend the table.
726 -- All this is done by allcoateGlobalBinder.
727 -- This is needed when *re*-compiling a module in GHCi; we must
728 -- use the same name for externally-visible things as we did before.
731 -----------------------------------------------------------
732 tidyTopPair :: VarEnv Bool
733 -> TidyEnv -- The TidyEnv is used to tidy the IdInfo
734 -- It is knot-tied: don't look at it!
737 -> (Id, CoreExpr) -- Binder and RHS before tidying
739 -- This function is the heart of Step 2
740 -- The rec_tidy_env is the one to use for the IdInfo
741 -- It's necessary because when we are dealing with a recursive
742 -- group, a variable late in the group might be mentioned
743 -- in the IdInfo of one early in the group
745 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
746 | isGlobalId bndr -- Injected binding for record selector, etc
747 = (bndr, tidyExpr rhs_tidy_env rhs)
751 bndr' = mkVanillaGlobal name' ty' idinfo'
752 ty' = tidyTopType (idType bndr)
753 rhs' = tidyExpr rhs_tidy_env rhs
755 idinfo' = tidyTopIdInfo (isJust maybe_external)
756 idinfo unfold_info worker_info
759 -- Expose an unfolding if ext_ids tells us to
760 -- Remember that ext_ids maps an Id to a Bool:
761 -- True to show the unfolding, False to hide it
762 maybe_external = lookupVarEnv ext_ids bndr
763 show_unfold = maybe_external `orElse` False
764 unfold_info | show_unfold = mkTopUnfolding rhs'
765 | otherwise = noUnfolding
766 worker_info = tidyWorker rhs_tidy_env show_unfold (workerInfo idinfo)
768 -- Usually the Id will have an accurate arity on it, because
769 -- the simplifier has just run, but not always.
770 -- One case I found was when the last thing the simplifier
771 -- did was to let-bind a non-atomic argument and then float
772 -- it to the top level. So it seems more robust just to
774 arity = exprArity rhs
777 -- tidyTopIdInfo creates the final IdInfo for top-level
778 -- binders. There are two delicate pieces:
780 -- * Arity. After CoreTidy, this arity must not change any more.
781 -- Indeed, CorePrep must eta expand where necessary to make
782 -- the manifest arity equal to the claimed arity.
784 -- * CAF info. This must also remain valid through to code generation.
785 -- We add the info here so that it propagates to all
786 -- occurrences of the binders in RHSs, and hence to occurrences in
787 -- unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
788 -- CoreToStg makes use of this when constructing SRTs.
789 tidyTopIdInfo :: Bool -> IdInfo -> Unfolding
790 -> WorkerInfo -> ArityInfo -> CafInfo
792 tidyTopIdInfo is_external idinfo unfold_info worker_info arity caf_info
793 | not is_external -- For internal Ids (not externally visible)
794 = vanillaIdInfo -- we only need enough info for code generation
795 -- Arity and strictness info are enough;
796 -- c.f. CoreTidy.tidyLetBndr
797 `setCafInfo` caf_info
799 `setAllStrictnessInfo` newStrictnessInfo idinfo
801 | otherwise -- Externally-visible Ids get the whole lot
803 `setCafInfo` caf_info
805 `setAllStrictnessInfo` newStrictnessInfo idinfo
806 `setInlinePragInfo` inlinePragInfo idinfo
807 `setUnfoldingInfo` unfold_info
808 `setWorkerInfo` worker_info
809 -- NB: we throw away the Rules
810 -- They have already been extracted by findExternalRules
814 ------------ Worker --------------
815 tidyWorker :: TidyEnv -> Bool -> WorkerInfo -> WorkerInfo
816 tidyWorker _tidy_env _show_unfold NoWorker
818 tidyWorker tidy_env show_unfold (HasWorker work_id wrap_arity)
819 | show_unfold = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
820 | otherwise = NoWorker
821 -- NB: do *not* expose the worker if show_unfold is off,
822 -- because that means this thing is a loop breaker or
823 -- marked NOINLINE or something like that
824 -- This is important: if you expose the worker for a loop-breaker
825 -- then you can make the simplifier go into an infinite loop, because
826 -- in effect the unfolding is exposed. See Trac #1709
828 -- You might think that if show_unfold is False, then the thing should
829 -- not be w/w'd in the first place. But a legitimate reason is this:
830 -- the function returns bottom
831 -- In this case, show_unfold will be false (we don't expose unfoldings
832 -- for bottoming functions), but we might still have a worker/wrapper
833 -- split (see Note [Worker-wrapper for bottoming functions] in WorkWrap.lhs
836 %************************************************************************
838 \subsection{Figuring out CafInfo for an expression}
840 %************************************************************************
842 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
843 We mark such things as `MayHaveCafRefs' because this information is
844 used to decide whether a particular closure needs to be referenced
847 There are two reasons for setting MayHaveCafRefs:
848 a) The RHS is a CAF: a top-level updatable thunk.
849 b) The RHS refers to something that MayHaveCafRefs
851 Possible improvement: In an effort to keep the number of CAFs (and
852 hence the size of the SRTs) down, we could also look at the expression and
853 decide whether it requires a small bounded amount of heap, so we can ignore
854 it as a CAF. In these cases however, we would need to use an additional
855 CAF list to keep track of non-collectable CAFs.
858 hasCafRefs :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
859 hasCafRefs this_pkg p arity expr
860 | is_caf || mentions_cafs
862 | otherwise = NoCafRefs
864 mentions_cafs = isFastTrue (cafRefs p expr)
865 is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
867 -- NB. we pass in the arity of the expression, which is expected
868 -- to be calculated by exprArity. This is because exprArity
869 -- knows how much eta expansion is going to be done by
870 -- CorePrep later on, and we don't want to duplicate that
871 -- knowledge in rhsIsStatic below.
873 cafRefs :: VarEnv Id -> Expr a -> FastBool
875 -- imported Ids first:
876 | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
877 -- now Ids local to this module:
879 case lookupVarEnv p id of
880 Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
881 Nothing -> fastBool False
883 cafRefs _ (Lit _) = fastBool False
884 cafRefs p (App f a) = fastOr (cafRefs p f) (cafRefs p) a
885 cafRefs p (Lam _ e) = cafRefs p e
886 cafRefs p (Let b e) = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
887 cafRefs p (Case e _bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
888 cafRefs p (Note _n e) = cafRefs p e
889 cafRefs p (Cast e _co) = cafRefs p e
890 cafRefs _ (Type _) = fastBool False
892 cafRefss :: VarEnv Id -> [Expr a] -> FastBool
893 cafRefss _ [] = fastBool False
894 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
896 fastOr :: FastBool -> (a -> FastBool) -> a -> FastBool
897 -- hack for lazy-or over FastBool.
898 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))