A bit of refactoring, plus a sanity check
[ghc-hetmet.git] / compiler / main / TidyPgm.lhs
1
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Tidying up Core}
5
6 \begin{code}
7 module TidyPgm( mkBootModDetailsDs, mkBootModDetailsTc, 
8                 tidyProgram, globaliseAndTidyId ) where
9
10 #include "HsVersions.h"
11
12 import TcRnTypes
13 import FamInstEnv
14 import DynFlags
15 import CoreSyn
16 import CoreUnfold
17 import CoreFVs
18 import CoreTidy
19 import CoreMonad
20 import CoreUtils
21 import CoreArity        ( exprArity, exprBotStrictness_maybe )
22 import Class            ( classSelIds )
23 import VarEnv
24 import VarSet
25 import Var
26 import Id
27 import IdInfo
28 import InstEnv
29 import Demand
30 import BasicTypes
31 import Name hiding (varName)
32 import NameSet
33 import IfaceEnv
34 import NameEnv
35 import TcType
36 import DataCon
37 import TyCon
38 import Module
39 import HscTypes
40 import Maybes
41 import ErrUtils
42 import UniqSupply
43 import Outputable
44 import FastBool hiding ( fastOr )
45 import Util
46
47 import Data.List        ( sortBy )
48 import Data.IORef       ( IORef, readIORef, writeIORef )
49 \end{code}
50
51
52 Constructing the TypeEnv, Instances, Rules, VectInfo from which the
53 ModIface is constructed, and which goes on to subsequent modules in
54 --make mode.
55
56 Most of the interface file is obtained simply by serialising the
57 TypeEnv.  One important consequence is that if the *interface file*
58 has pragma info if and only if the final TypeEnv does. This is not so
59 important for *this* module, but it's essential for ghc --make:
60 subsequent compilations must not see (e.g.) the arity if the interface
61 file does not contain arity If they do, they'll exploit the arity;
62 then the arity might change, but the iface file doesn't change =>
63 recompilation does not happen => disaster. 
64
65 For data types, the final TypeEnv will have a TyThing for the TyCon,
66 plus one for each DataCon; the interface file will contain just one
67 data type declaration, but it is de-serialised back into a collection
68 of TyThings.
69
70 %************************************************************************
71 %*                                                                      *
72                 Plan A: simpleTidyPgm
73 %*                                                                      * 
74 %************************************************************************
75
76
77 Plan A: mkBootModDetails: omit pragmas, make interfaces small
78 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
79 * Ignore the bindings
80
81 * Drop all WiredIn things from the TypeEnv 
82         (we never want them in interface files)
83
84 * Retain all TyCons and Classes in the TypeEnv, to avoid
85         having to find which ones are mentioned in the
86         types of exported Ids
87
88 * Trim off the constructors of non-exported TyCons, both
89         from the TyCon and from the TypeEnv
90
91 * Drop non-exported Ids from the TypeEnv
92
93 * Tidy the types of the DFunIds of Instances, 
94   make them into GlobalIds, (they already have External Names)
95   and add them to the TypeEnv
96
97 * Tidy the types of the (exported) Ids in the TypeEnv,
98   make them into GlobalIds (they already have External Names)
99
100 * Drop rules altogether
101
102 * Tidy the bindings, to ensure that the Caf and Arity
103   information is correct for each top-level binder; the 
104   code generator needs it. And to ensure that local names have
105   distinct OccNames in case of object-file splitting
106
107 \begin{code}
108 -- This is Plan A: make a small type env when typechecking only,
109 -- or when compiling a hs-boot file, or simply when not using -O
110 --
111 -- We don't look at the bindings at all -- there aren't any
112 -- for hs-boot files
113
114 mkBootModDetailsTc :: HscEnv -> TcGblEnv -> IO ModDetails
115 mkBootModDetailsTc hsc_env 
116         TcGblEnv{ tcg_exports   = exports,
117                   tcg_type_env  = type_env,
118                   tcg_insts     = insts,
119                   tcg_fam_insts = fam_insts
120                 }
121   = mkBootModDetails hsc_env exports type_env insts fam_insts
122
123 mkBootModDetailsDs :: HscEnv -> ModGuts -> IO ModDetails
124 mkBootModDetailsDs hsc_env 
125         ModGuts{ mg_exports   = exports,
126                  mg_types     = type_env,
127                  mg_insts     = insts,
128                  mg_fam_insts = fam_insts
129                 }
130   = mkBootModDetails hsc_env exports type_env insts fam_insts
131   
132 mkBootModDetails :: HscEnv -> [AvailInfo] -> NameEnv TyThing
133                  -> [Instance] -> [FamInstEnv.FamInst] -> IO ModDetails
134 mkBootModDetails hsc_env exports type_env insts fam_insts
135   = do  { let dflags = hsc_dflags hsc_env 
136         ; showPass dflags "Tidy [hoot] type env"
137
138         ; let { insts'     = tidyInstances globaliseAndTidyId insts
139               ; dfun_ids   = map instanceDFunId insts'
140               ; type_env1  = tidyBootTypeEnv (availsToNameSet exports) type_env
141               ; type_env'  = extendTypeEnvWithIds type_env1 dfun_ids
142               }
143         ; return (ModDetails { md_types     = type_env'
144                              , md_insts     = insts'
145                              , md_fam_insts = fam_insts
146                              , md_rules     = []
147                              , md_anns      = []
148                              , md_exports   = exports
149                              , md_vect_info = noVectInfo
150                              })
151         }
152   where
153
154 tidyBootTypeEnv :: NameSet -> TypeEnv -> TypeEnv
155 tidyBootTypeEnv exports type_env 
156   = tidyTypeEnv True False exports type_env final_ids
157   where
158         -- Find the LocalIds in the type env that are exported
159         -- Make them into GlobalIds, and tidy their types
160         --
161         -- It's very important to remove the non-exported ones
162         -- because we don't tidy the OccNames, and if we don't remove
163         -- the non-exported ones we'll get many things with the
164         -- same name in the interface file, giving chaos.
165     final_ids = [ globaliseAndTidyId id
166                 | id <- typeEnvIds type_env
167                 , isLocalId id
168                 , keep_it id ]
169
170         -- default methods have their export flag set, but everything
171         -- else doesn't (yet), because this is pre-desugaring, so we
172         -- must test both.
173     keep_it id = isExportedId id || idName id `elemNameSet` exports
174
175
176
177 globaliseAndTidyId :: Id -> Id
178 -- Takes an LocalId with an External Name, 
179 -- makes it into a GlobalId 
180 --     * unchanged Name (might be Internal or External)
181 --     * unchanged details
182 --     * VanillaIdInfo (makes a conservative assumption about Caf-hood)
183 globaliseAndTidyId id   
184   = Id.setIdType (globaliseId id) tidy_type
185   where
186     tidy_type = tidyTopType (idType id)
187 \end{code}
188
189
190 %************************************************************************
191 %*                                                                      *
192         Plan B: tidy bindings, make TypeEnv full of IdInfo
193 %*                                                                      * 
194 %************************************************************************
195
196 Plan B: include pragmas, make interfaces 
197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 * Figure out which Ids are externally visible
199
200 * Tidy the bindings, externalising appropriate Ids
201
202 * Drop all Ids from the TypeEnv, and add all the External Ids from 
203   the bindings.  (This adds their IdInfo to the TypeEnv; and adds
204   floated-out Ids that weren't even in the TypeEnv before.)
205
206 Step 1: Figure out external Ids
207 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
208 Note [choosing external names]
209
210 See also the section "Interface stability" in the
211 RecompilationAvoidance commentary:
212   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
213
214 First we figure out which Ids are "external" Ids.  An
215 "external" Id is one that is visible from outside the compilation
216 unit.  These are
217         a) the user exported ones
218         b) ones mentioned in the unfoldings, workers, 
219            or rules of externally-visible ones 
220
221 While figuring out which Ids are external, we pick a "tidy" OccName
222 for each one.  That is, we make its OccName distinct from the other
223 external OccNames in this module, so that in interface files and
224 object code we can refer to it unambiguously by its OccName.  The
225 OccName for each binder is prefixed by the name of the exported Id
226 that references it; e.g. if "f" references "x" in its unfolding, then
227 "x" is renamed to "f_x".  This helps distinguish the different "x"s
228 from each other, and means that if "f" is later removed, things that
229 depend on the other "x"s will not need to be recompiled.  Of course,
230 if there are multiple "f_x"s, then we have to disambiguate somehow; we
231 use "f_x0", "f_x1" etc.
232
233 As far as possible we should assign names in a deterministic fashion.
234 Each time this module is compiled with the same options, we should end
235 up with the same set of external names with the same types.  That is,
236 the ABI hash in the interface should not change.  This turns out to be
237 quite tricky, since the order of the bindings going into the tidy
238 phase is already non-deterministic, as it is based on the ordering of
239 Uniques, which are assigned unpredictably.
240
241 To name things in a stable way, we do a depth-first-search of the
242 bindings, starting from the exports sorted by name.  This way, as long
243 as the bindings themselves are deterministic (they sometimes aren't!),
244 the order in which they are presented to the tidying phase does not
245 affect the names we assign.
246
247 Step 2: Tidy the program
248 ~~~~~~~~~~~~~~~~~~~~~~~~
249 Next we traverse the bindings top to bottom.  For each *top-level*
250 binder
251
252  1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal, 
253     reflecting the fact that from now on we regard it as a global, 
254     not local, Id
255
256  2. Give it a system-wide Unique.
257     [Even non-exported things need system-wide Uniques because the
258     byte-code generator builds a single Name->BCO symbol table.]
259
260     We use the NameCache kept in the HscEnv as the
261     source of such system-wide uniques.
262
263     For external Ids, use the original-name cache in the NameCache
264     to ensure that the unique assigned is the same as the Id had 
265     in any previous compilation run.
266
267  3. Rename top-level Ids according to the names we chose in step 1.
268     If it's an external Id, make it have a External Name, otherwise
269     make it have an Internal Name.  This is used by the code generator
270     to decide whether to make the label externally visible
271
272  4. Give it its UTTERLY FINAL IdInfo; in ptic, 
273         * its unfolding, if it should have one
274         
275         * its arity, computed from the number of visible lambdas
276
277         * its CAF info, computed from what is free in its RHS
278
279                 
280 Finally, substitute these new top-level binders consistently
281 throughout, including in unfoldings.  We also tidy binders in
282 RHSs, so that they print nicely in interfaces.
283
284 \begin{code}
285 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
286 tidyProgram hsc_env  (ModGuts { mg_module = mod, mg_exports = exports, 
287                                 mg_types = type_env, 
288                                 mg_insts = insts, mg_fam_insts = fam_insts,
289                                 mg_binds = binds, 
290                                 mg_rules = imp_rules,
291                                 mg_vect_info = vect_info,
292                                 mg_dir_imps = dir_imps, 
293                                 mg_anns = anns,
294                                 mg_deps = deps, 
295                                 mg_foreign = foreign_stubs,
296                                 mg_hpc_info = hpc_info,
297                                 mg_modBreaks = modBreaks })
298
299   = do  { let { dflags     = hsc_dflags hsc_env
300               ; omit_prags = dopt Opt_OmitInterfacePragmas dflags
301               ; expose_all = dopt Opt_ExposeAllUnfoldings  dflags
302               ; th         = dopt Opt_TemplateHaskell      dflags
303               }
304         ; showPass dflags "Tidy Core"
305
306         ; let { implicit_binds = getImplicitBinds type_env }
307
308         ; (unfold_env, tidy_occ_env)
309               <- chooseExternalIds hsc_env mod omit_prags expose_all 
310                                    binds implicit_binds imp_rules
311
312         ; let { ext_rules = findExternalRules omit_prags binds imp_rules unfold_env }
313                 -- Glom together imp_rules and rules currently attached to binders
314                 -- Then pick just the ones we need to expose
315                 -- See Note [Which rules to expose]
316
317         ; let { (tidy_env, tidy_binds)
318                  = tidyTopBinds hsc_env unfold_env tidy_occ_env binds }
319
320         ; let { export_set = availsToNameSet exports
321               ; final_ids  = [ id | id <- bindersOfBinds tidy_binds, 
322                                     isExternalName (idName id)]
323               ; tidy_type_env = tidyTypeEnv omit_prags th export_set
324                                             type_env final_ids
325               ; tidy_insts    = tidyInstances (lookup_dfun tidy_type_env) insts
326                 -- A DFunId will have a binding in tidy_binds, and so
327                 -- will now be in final_env, replete with IdInfo
328                 -- Its name will be unchanged since it was born, but
329                 -- we want Global, IdInfo-rich (or not) DFunId in the
330                 -- tidy_insts
331
332               ; tidy_rules = tidyRules tidy_env ext_rules
333                 -- You might worry that the tidy_env contains IdInfo-rich stuff
334                 -- and indeed it does, but if omit_prags is on, ext_rules is
335                 -- empty
336
337               ; tidy_vect_info = tidyVectInfo tidy_env vect_info
338
339               -- See Note [Injecting implicit bindings]
340               ; all_tidy_binds = implicit_binds ++ tidy_binds
341
342               ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
343               }
344
345         ; endPass dflags "Tidy Core" Opt_D_dump_simpl all_tidy_binds tidy_rules
346         ; let dir_imp_mods = moduleEnvKeys dir_imps
347
348         ; return (CgGuts { cg_module   = mod, 
349                            cg_tycons   = alg_tycons,
350                            cg_binds    = all_tidy_binds,
351                            cg_dir_imps = dir_imp_mods,
352                            cg_foreign  = foreign_stubs,
353                            cg_dep_pkgs = dep_pkgs deps,
354                            cg_hpc_info = hpc_info,
355                            cg_modBreaks = modBreaks }, 
356
357                    ModDetails { md_types     = tidy_type_env,
358                                 md_rules     = tidy_rules,
359                                 md_insts     = tidy_insts,
360                                 md_vect_info = tidy_vect_info,
361                                 md_fam_insts = fam_insts,
362                                 md_exports   = exports,
363                                 md_anns      = anns      -- are already tidy
364                               })
365         }
366
367 lookup_dfun :: TypeEnv -> Var -> Id
368 lookup_dfun type_env dfun_id
369   = case lookupTypeEnv type_env (idName dfun_id) of
370         Just (AnId dfun_id') -> dfun_id'
371         _other -> pprPanic "lookup_dfun" (ppr dfun_id)
372
373 --------------------------
374 tidyTypeEnv :: Bool     -- Compiling without -O, so omit prags
375             -> Bool     -- Template Haskell is on
376             -> NameSet -> TypeEnv -> [Id] -> TypeEnv
377
378 -- The competed type environment is gotten from
379 --      Dropping any wired-in things, and then
380 --      a) keeping the types and classes
381 --      b) removing all Ids, 
382 --      c) adding Ids with correct IdInfo, including unfoldings,
383 --              gotten from the bindings
384 -- From (c) we keep only those Ids with External names;
385 --          the CoreTidy pass makes sure these are all and only
386 --          the externally-accessible ones
387 -- This truncates the type environment to include only the 
388 -- exported Ids and things needed from them, which saves space
389
390 tidyTypeEnv omit_prags th exports type_env final_ids
391  = let  type_env1 = filterNameEnv keep_it type_env
392         type_env2 = extendTypeEnvWithIds type_env1 final_ids
393         type_env3 | omit_prags = mapNameEnv (trimThing th exports) type_env2
394                   | otherwise  = type_env2
395     in 
396     type_env3
397   where
398         -- We keep GlobalIds, because they won't appear 
399         -- in the bindings from which final_ids are derived!
400         -- (The bindings bind LocalIds.)
401     keep_it thing | isWiredInThing thing = False
402     keep_it (AnId id) = isGlobalId id   -- Keep GlobalIds (e.g. class ops)
403     keep_it _other    = True            -- Keep all TyCons, DataCons, and Classes
404
405 --------------------------
406 isWiredInThing :: TyThing -> Bool
407 isWiredInThing thing = isWiredInName (getName thing)
408
409 --------------------------
410 trimThing :: Bool -> NameSet -> TyThing -> TyThing
411 -- Trim off inessentials, for boot files and no -O
412 trimThing th exports (ATyCon tc)
413    | not th && not (mustExposeTyCon exports tc)
414    = ATyCon (makeTyConAbstract tc)      -- Note [Trimming and Template Haskell]
415
416 trimThing _th _exports (AnId id)
417    | not (isImplicitId id) 
418    = AnId (id `setIdInfo` vanillaIdInfo)
419
420 trimThing _th _exports other_thing 
421   = other_thing
422
423
424 {- Note [Trimming and Template Haskell]
425    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
426 Consider (Trac #2386) this
427         module M(T, makeOne) where
428           data T = Yay String
429           makeOne = [| Yay "Yep" |]
430 Notice that T is exported abstractly, but makeOne effectively exports it too!
431 A module that splices in $(makeOne) will then look for a declartion of Yay,
432 so it'd better be there.  Hence, brutally but simply, we switch off type
433 constructor trimming if TH is enabled in this module. -}
434
435
436 mustExposeTyCon :: NameSet      -- Exports
437                 -> TyCon        -- The tycon
438                 -> Bool         -- Can its rep be hidden?
439 -- We are compiling without -O, and thus trying to write as little as 
440 -- possible into the interface file.  But we must expose the details of
441 -- any data types whose constructors or fields are exported
442 mustExposeTyCon exports tc
443   | not (isAlgTyCon tc)         -- Synonyms
444   = True
445   | isEnumerationTyCon tc       -- For an enumeration, exposing the constructors
446   = True                        -- won't lead to the need for further exposure
447                                 -- (This includes data types with no constructors.)
448   | isOpenTyCon tc              -- Open type family
449   = True
450
451   | otherwise                   -- Newtype, datatype
452   = any exported_con (tyConDataCons tc)
453         -- Expose rep if any datacon or field is exported
454
455   || (isNewTyCon tc && isFFITy (snd (newTyConRhs tc)))
456         -- Expose the rep for newtypes if the rep is an FFI type.  
457         -- For a very annoying reason.  'Foreign import' is meant to
458         -- be able to look through newtypes transparently, but it
459         -- can only do that if it can "see" the newtype representation
460   where
461     exported_con con = any (`elemNameSet` exports) 
462                            (dataConName con : dataConFieldLabels con)
463
464 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
465 tidyInstances tidy_dfun ispecs
466   = map tidy ispecs
467   where
468     tidy ispec = setInstanceDFunId ispec $
469                  tidy_dfun (instanceDFunId ispec)
470 \end{code}
471
472 \begin{code}
473 tidyVectInfo :: TidyEnv -> VectInfo -> VectInfo
474 tidyVectInfo (_, var_env) info@(VectInfo { vectInfoVar     = vars
475                                          , vectInfoPADFun  = pas
476                                          , vectInfoIso     = isos })
477   = info { vectInfoVar    = tidy_vars
478          , vectInfoPADFun = tidy_pas
479          , vectInfoIso    = tidy_isos }
480   where
481     tidy_vars = mkVarEnv
482               $ map tidy_var_mapping
483               $ varEnvElts vars
484
485     tidy_pas = mapNameEnv tidy_snd_var pas
486     tidy_isos = mapNameEnv tidy_snd_var isos
487
488     tidy_var_mapping (from, to) = (from', (from', lookup_var to))
489       where from' = lookup_var from
490     tidy_snd_var (x, var) = (x, lookup_var var)
491       
492     lookup_var var = lookupWithDefaultVarEnv var_env var var
493 \end{code}
494
495
496 %************************************************************************
497 %*                                                                      *
498         Implicit bindings
499 %*                                                                      *
500 %************************************************************************
501
502 Note [Injecting implicit bindings]
503 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
504 We inject the implict bindings right at the end, in CoreTidy.
505 Some of these bindings, notably record selectors, are not
506 constructed in an optimised form.  E.g. record selector for
507         data T = MkT { x :: {-# UNPACK #-} !Int }
508 Then the unfolding looks like
509         x = \t. case t of MkT x1 -> let x = I# x1 in x
510 This generates bad code unless it's first simplified a bit.  That is
511 why CoreUnfold.mkImplicitUnfolding uses simleExprOpt to do a bit of
512 optimisation first.  (Only matters when the selector is used curried;
513 eg map x ys.)  See Trac #2070.
514
515 [Oct 09: in fact, record selectors are no longer implicit Ids at all,
516 because we really do want to optimise them properly. They are treated
517 much like any other Id.  But doing "light" optimisation on an implicit
518 Id still makes sense.]
519
520 At one time I tried injecting the implicit bindings *early*, at the
521 beginning of SimplCore.  But that gave rise to real difficulty,
522 becuase GlobalIds are supposed to have *fixed* IdInfo, but the
523 simplifier and other core-to-core passes mess with IdInfo all the
524 time.  The straw that broke the camels back was when a class selector
525 got the wrong arity -- ie the simplifier gave it arity 2, whereas
526 importing modules were expecting it to have arity 1 (Trac #2844).
527 It's much safer just to inject them right at the end, after tidying.
528
529 Oh: two other reasons for injecting them late:
530
531   - If implicit Ids are already in the bindings when we start TidyPgm,
532     we'd have to be careful not to treat them as external Ids (in
533     the sense of findExternalIds); else the Ids mentioned in *their*
534     RHSs will be treated as external and you get an interface file 
535     saying      a18 = <blah>
536     but nothing refererring to a18 (because the implicit Id is the 
537     one that does, and implicit Ids don't appear in interface files).
538
539   - More seriously, the tidied type-envt will include the implicit
540     Id replete with a18 in its unfolding; but we won't take account
541     of a18 when computing a fingerprint for the class; result chaos.
542     
543 There is one sort of implicit binding that is injected still later,
544 namely those for data constructor workers. Reason (I think): it's
545 really just a code generation trick.... binding itself makes no sense.
546 See CorePrep Note [Data constructor workers].
547
548 \begin{code}
549 getImplicitBinds :: TypeEnv -> [CoreBind]
550 getImplicitBinds type_env
551   = map get_defn (concatMap implicit_ids (typeEnvElts type_env))
552   where
553     implicit_ids (ATyCon tc)  = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
554     implicit_ids (AClass cls) = classSelIds cls
555     implicit_ids _            = []
556     
557     get_defn :: Id -> CoreBind
558     get_defn id = NonRec id (unfoldingTemplate (realIdUnfolding id))
559 \end{code}
560
561
562 %************************************************************************
563 %*                                                                      *
564 \subsection{Step 1: finding externals}
565 %*                                                                      * 
566 %************************************************************************
567
568 Sete Note [choosing external names].
569
570 \begin{code}
571 type UnfoldEnv  = IdEnv (Name{-new name-}, Bool {-show unfolding-})
572   -- Maps each top-level Id to its new Name (the Id is tidied in step 2)
573   -- The Unique is unchanged.  If the new Name is external, it will be
574   -- visible in the interface file.  
575   --
576   -- Bool => expose unfolding or not.
577
578 chooseExternalIds :: HscEnv
579                   -> Module
580                   -> Bool -> Bool
581                   -> [CoreBind]
582                   -> [CoreBind]
583                   -> [CoreRule]
584                   -> IO (UnfoldEnv, TidyOccEnv)
585         -- Step 1 from the notes above
586
587 chooseExternalIds hsc_env mod omit_prags expose_all binds implicit_binds imp_id_rules
588   = do { (unfold_env1,occ_env1) <- search init_work_list emptyVarEnv init_occ_env
589        ; let internal_ids = filter (not . (`elemVarEnv` unfold_env1)) binders
590        ; tidy_internal internal_ids unfold_env1 occ_env1 }
591  where
592   nc_var = hsc_NC hsc_env 
593
594   -- init_ext_ids is the intial list of Ids that should be
595   -- externalised.  It serves as the starting point for finding a
596   -- deterministic, tidy, renaming for all external Ids in this
597   -- module.
598   -- 
599   -- It is sorted, so that it has adeterministic order (i.e. it's the
600   -- same list every time this module is compiled), in contrast to the
601   -- bindings, which are ordered non-deterministically.
602   init_work_list = zip init_ext_ids init_ext_ids
603   init_ext_ids   = sortBy (compare `on` getOccName) $
604                    filter is_external binders
605
606   -- An Id should be external if either (a) it is exported or
607   -- (b) it appears in the RHS of a local rule for an imported Id.   
608   -- See Note [Which rules to expose]
609   is_external id = isExportedId id || id `elemVarSet` rule_rhs_vars
610   rule_rhs_vars = foldr (unionVarSet . ruleRhsFreeVars) emptyVarSet imp_id_rules
611
612   binders          = bindersOfBinds binds
613   implicit_binders = bindersOfBinds implicit_binds
614   binder_set       = mkVarSet binders
615
616   avoids   = [getOccName name | bndr <- binders ++ implicit_binders,
617                                 let name = idName bndr,
618                                 isExternalName name ]
619                 -- In computing our "avoids" list, we must include
620                 --      all implicit Ids
621                 --      all things with global names (assigned once and for
622                 --                                      all by the renamer)
623                 -- since their names are "taken".
624                 -- The type environment is a convenient source of such things.
625                 -- In particular, the set of binders doesn't include
626                 -- implicit Ids at this stage.
627
628         -- We also make sure to avoid any exported binders.  Consider
629         --      f{-u1-} = 1     -- Local decl
630         --      ...
631         --      f{-u2-} = 2     -- Exported decl
632         --
633         -- The second exported decl must 'get' the name 'f', so we
634         -- have to put 'f' in the avoids list before we get to the first
635         -- decl.  tidyTopId then does a no-op on exported binders.
636   init_occ_env = initTidyOccEnv avoids
637
638
639   search :: [(Id,Id)]    -- The work-list: (external id, referrring id)
640                          -- Make a tidy, external Name for the external id,
641                          --   add it to the UnfoldEnv, and do the same for the
642                          --   transitive closure of Ids it refers to
643                          -- The referring id is used to generate a tidy
644                          ---  name for the external id
645          -> UnfoldEnv    -- id -> (new Name, show_unfold)
646          -> TidyOccEnv   -- occ env for choosing new Names
647          -> IO (UnfoldEnv, TidyOccEnv)
648
649   search [] unfold_env occ_env = return (unfold_env, occ_env)
650
651   search ((idocc,referrer) : rest) unfold_env occ_env
652     | idocc `elemVarEnv` unfold_env = search rest unfold_env occ_env
653     | otherwise = do
654       (occ_env', name') <- tidyTopName mod nc_var (Just referrer) occ_env idocc
655       let 
656           (new_ids, show_unfold)
657                 | omit_prags = ([], False)
658                 | otherwise  = addExternal expose_all refined_id
659
660                 -- 'idocc' is an *occurrence*, but we need to see the
661                 -- unfolding in the *definition*; so look up in binder_set
662           refined_id = case lookupVarSet binder_set idocc of
663                          Just id -> id
664                          Nothing -> WARN( True, ppr idocc ) idocc
665
666           unfold_env' = extendVarEnv unfold_env idocc (name',show_unfold)
667           referrer' | isExportedId refined_id = refined_id
668                     | otherwise               = referrer
669       --
670       search (zip new_ids (repeat referrer') ++ rest) unfold_env' occ_env'
671
672   tidy_internal :: [Id] -> UnfoldEnv -> TidyOccEnv
673                 -> IO (UnfoldEnv, TidyOccEnv)
674   tidy_internal []       unfold_env occ_env = return (unfold_env,occ_env)
675   tidy_internal (id:ids) unfold_env occ_env = do
676       (occ_env', name') <- tidyTopName mod nc_var Nothing occ_env id
677       let unfold_env' = extendVarEnv unfold_env id (name',False)
678       tidy_internal ids unfold_env' occ_env'
679
680 addExternal :: Bool -> Id -> ([Id],Bool)
681 addExternal expose_all id = (new_needed_ids, show_unfold)
682   where
683     new_needed_ids = unfold_ids ++
684                      filter (\id -> isLocalId id &&
685                                     not (id `elemVarSet` unfold_set))
686                        (varSetElems spec_ids) -- XXX non-det ordering
687
688     idinfo         = idInfo id
689     never_active   = isNeverActive (inlinePragmaActivation (inlinePragInfo idinfo))
690     loop_breaker   = isNonRuleLoopBreaker (occInfo idinfo)
691     bottoming_fn   = isBottomingSig (strictnessInfo idinfo `orElse` topSig)
692     spec_ids       = specInfoFreeVars (specInfo idinfo)
693
694         -- Stuff to do with the Id's unfolding
695         -- We leave the unfolding there even if there is a worker
696         -- In GHCI the unfolding is used by importers
697     show_unfold = isJust mb_unfold_ids
698     (unfold_set, unfold_ids) = mb_unfold_ids `orElse` (emptyVarSet, [])
699
700     mb_unfold_ids :: Maybe (IdSet, [Id])        -- Nothing => don't unfold
701     mb_unfold_ids = case unfoldingInfo idinfo of
702                       CoreUnfolding { uf_tmpl = unf_rhs, uf_src = src, uf_guidance = guide } 
703                         | show_unfolding src guide
704                         -> Just (exprFvsInOrder unf_rhs)
705                       DFunUnfolding _ ops -> Just (exprsFvsInOrder ops)
706                       _                   -> Nothing
707
708     show_unfolding unf_source unf_guidance
709        =  expose_all         -- 'expose_all' says to expose all 
710                              -- unfoldings willy-nilly
711
712        || isInlineRuleSource unf_source      -- Always expose things whose 
713                                              -- source is an inline rule
714
715        || not (bottoming_fn      -- No need to inline bottom functions
716            || never_active       -- Or ones that say not to
717            || loop_breaker       -- Or that are loop breakers
718            || neverUnfoldGuidance unf_guidance)
719
720 -- We want a deterministic free-variable list.  exprFreeVars gives us
721 -- a VarSet, which is in a non-deterministic order when converted to a
722 -- list.  Hence, here we define a free-variable finder that returns
723 -- the free variables in the order that they are encountered.
724 --
725 -- Note [choosing external names]
726
727 exprFvsInOrder :: CoreExpr -> (VarSet, [Id])
728 exprFvsInOrder e = run (dffvExpr e)
729
730 exprsFvsInOrder :: [CoreExpr] -> (VarSet, [Id])
731 exprsFvsInOrder es = run (mapM_ dffvExpr es)
732
733 run :: DFFV () -> (VarSet, [Id])
734 run (DFFV m) = case m emptyVarSet [] of
735                  (set,ids,_) -> (set,ids)
736
737 newtype DFFV a = DFFV (VarSet -> [Var] -> (VarSet,[Var],a))
738
739 instance Monad DFFV where
740   return a = DFFV $ \set ids -> (set, ids, a)
741   (DFFV m) >>= k = DFFV $ \set ids ->
742     case m set ids of
743        (set',ids',a) -> case k a of
744                           DFFV f -> f set' ids' 
745
746 insert :: Var -> DFFV ()
747 insert v = DFFV $ \ set ids  -> case () of 
748  _ | v `elemVarSet` set -> (set,ids,())
749    | otherwise          -> (extendVarSet set v, v:ids, ())
750
751 dffvExpr :: CoreExpr -> DFFV ()
752 dffvExpr e = go emptyVarSet e
753   where
754     go scope e = case e of
755       Var v | isLocalId v && not (v `elemVarSet` scope) -> insert v
756       App e1 e2          -> do go scope e1; go scope e2
757       Lam v e            -> go (extendVarSet scope v) e
758       Note _ e           -> go scope e
759       Cast e _           -> go scope e
760       Let (NonRec x r) e -> do go scope r; go (extendVarSet scope x) e
761       Let (Rec prs) e    -> do let scope' = extendVarSetList scope (map fst prs)
762                                mapM_ (go scope') (map snd prs)
763                                go scope' e
764       Case e b _ as      -> do go scope e
765                                mapM_ (go_alt (extendVarSet scope b)) as
766       _other             -> return ()
767
768     go_alt scope (_,xs,r) = go (extendVarSetList scope xs) r
769 \end{code}
770
771
772 --------------------------------------------------------------------
773 --              tidyTopName
774 -- This is where we set names to local/global based on whether they really are 
775 -- externally visible (see comment at the top of this module).  If the name
776 -- was previously local, we have to give it a unique occurrence name if
777 -- we intend to externalise it.
778
779 \begin{code}
780 tidyTopName :: Module -> IORef NameCache -> Maybe Id -> TidyOccEnv
781             -> Id -> IO (TidyOccEnv, Name)
782 tidyTopName mod nc_var maybe_ref occ_env id
783   | global && internal = return (occ_env, localiseName name)
784
785   | global && external = return (occ_env, name)
786         -- Global names are assumed to have been allocated by the renamer,
787         -- so they already have the "right" unique
788         -- And it's a system-wide unique too
789
790   -- Now we get to the real reason that all this is in the IO Monad:
791   -- we have to update the name cache in a nice atomic fashion
792
793   | local  && internal = do { nc <- readIORef nc_var
794                             ; let (nc', new_local_name) = mk_new_local nc
795                             ; writeIORef nc_var nc'
796                             ; return (occ_env', new_local_name) }
797         -- Even local, internal names must get a unique occurrence, because
798         -- if we do -split-objs we externalise the name later, in the code generator
799         --
800         -- Similarly, we must make sure it has a system-wide Unique, because
801         -- the byte-code generator builds a system-wide Name->BCO symbol table
802
803   | local  && external = do { nc <- readIORef nc_var
804                             ; let (nc', new_external_name) = mk_new_external nc
805                             ; writeIORef nc_var nc'
806                             ; return (occ_env', new_external_name) }
807
808   | otherwise = panic "tidyTopName"
809   where
810     name        = idName id
811     external    = isJust maybe_ref
812     global      = isExternalName name
813     local       = not global
814     internal    = not external
815     loc         = nameSrcSpan name
816
817     old_occ     = nameOccName name
818     new_occ
819       | Just ref <- maybe_ref, ref /= id = 
820           mkOccName (occNameSpace old_occ) $
821              let
822                  ref_str = occNameString (getOccName ref)
823                  occ_str = occNameString old_occ
824              in
825              case occ_str of
826                '$':'w':_ -> occ_str
827                   -- workers: the worker for a function already
828                   -- includes the occname for its parent, so there's
829                   -- no need to prepend the referrer.
830                _other | isSystemName name -> ref_str
831                       | otherwise         -> ref_str ++ '_' : occ_str
832                   -- If this name was system-generated, then don't bother
833                   -- to retain its OccName, just use the referrer.  These
834                   -- system-generated names will become "f1", "f2", etc. for
835                   -- a referrer "f".
836       | otherwise = old_occ
837
838     (occ_env', occ') = tidyOccName occ_env new_occ
839
840     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
841                     where
842                       (us1, us2) = splitUniqSupply (nsUniqs nc)
843                       uniq       = uniqFromSupply us1
844
845     mk_new_external nc = allocateGlobalBinder nc mod occ' loc
846         -- If we want to externalise a currently-local name, check
847         -- whether we have already assigned a unique for it.
848         -- If so, use it; if not, extend the table.
849         -- All this is done by allcoateGlobalBinder.
850         -- This is needed when *re*-compiling a module in GHCi; we must
851         -- use the same name for externally-visible things as we did before.
852 \end{code}
853
854 \begin{code}
855 findExternalRules :: Bool       -- Omit pragmas
856                   -> [CoreBind]
857                   -> [CoreRule] -- Local rules for imported fns
858                   -> UnfoldEnv  -- Ids that are exported, so we need their rules
859                   -> [CoreRule]
860   -- The complete rules are gotten by combining
861   --    a) local rules for imported Ids
862   --    b) rules embedded in the top-level Ids
863 findExternalRules omit_prags binds imp_id_rules unfold_env
864   | omit_prags = []
865   | otherwise  = filterOut internal_rule (imp_id_rules ++ local_rules)
866   where
867     local_rules  = [ rule
868                    | id <- bindersOfBinds binds,
869                      external_id id,
870                      rule <- idCoreRules id
871                    ]
872
873     internal_rule rule
874         =  any (not . external_id) (varSetElems (ruleLhsFreeIds rule))
875                 -- Don't export a rule whose LHS mentions a locally-defined
876                 --  Id that is completely internal (i.e. not visible to an
877                 -- importing module)
878
879     external_id id
880       | Just (name,_) <- lookupVarEnv unfold_env id = isExternalName name
881       | otherwise = False
882 \end{code}
883
884 Note [Which rules to expose]
885 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
886 findExternalRules filters imp_rules to avoid binders that 
887 aren't externally visible; but the externally-visible binders 
888 are computed (by findExternalIds) assuming that all orphan
889 rules are externalised (see init_ext_ids in function 
890 'search'). So in fact we may export more than we need. 
891 (It's a sort of mutual recursion.)
892
893 %************************************************************************
894 %*                                                                      *
895 \subsection{Step 2: top-level tidying}
896 %*                                                                      *
897 %************************************************************************
898
899
900 \begin{code}
901 -- TopTidyEnv: when tidying we need to know
902 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
903 --        These may have arisen because the
904 --        renamer read in an interface file mentioning M.$wf, say,
905 --        and assigned it unique r77.  If, on this compilation, we've
906 --        invented an Id whose name is $wf (but with a different unique)
907 --        we want to rename it to have unique r77, so that we can do easy
908 --        comparisons with stuff from the interface file
909 --
910 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
911 --     are 'used'
912 --
913 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
914
915 tidyTopBinds :: HscEnv
916              -> UnfoldEnv
917              -> TidyOccEnv
918              -> [CoreBind]
919              -> (TidyEnv, [CoreBind])
920
921 tidyTopBinds hsc_env unfold_env init_occ_env binds
922   = tidy init_env binds
923   where
924     init_env = (init_occ_env, emptyVarEnv)
925
926     this_pkg = thisPackage (hsc_dflags hsc_env)
927
928     tidy env []     = (env, [])
929     tidy env (b:bs) = let (env1, b')  = tidyTopBind this_pkg unfold_env env b
930                           (env2, bs') = tidy env1 bs
931                       in
932                           (env2, b':bs')
933
934 ------------------------
935 tidyTopBind  :: PackageId
936              -> UnfoldEnv
937              -> TidyEnv
938              -> CoreBind
939              -> (TidyEnv, CoreBind)
940
941 tidyTopBind this_pkg unfold_env (occ_env,subst1) (NonRec bndr rhs)
942   = (tidy_env2,  NonRec bndr' rhs')
943   where
944     Just (name',show_unfold) = lookupVarEnv unfold_env bndr
945     caf_info      = hasCafRefs this_pkg subst1 (idArity bndr) rhs
946     (bndr', rhs') = tidyTopPair show_unfold tidy_env2 caf_info name' (bndr, rhs)
947     subst2        = extendVarEnv subst1 bndr bndr'
948     tidy_env2     = (occ_env, subst2)
949
950 tidyTopBind this_pkg unfold_env (occ_env,subst1) (Rec prs)
951   = (tidy_env2, Rec prs')
952   where
953     prs' = [ tidyTopPair show_unfold tidy_env2 caf_info name' (id,rhs)
954            | (id,rhs) <- prs,
955              let (name',show_unfold) = 
956                     expectJust "tidyTopBind" $ lookupVarEnv unfold_env id
957            ]
958
959     subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
960     tidy_env2 = (occ_env, subst2)
961
962     bndrs = map fst prs
963
964         -- the CafInfo for a recursive group says whether *any* rhs in
965         -- the group may refer indirectly to a CAF (because then, they all do).
966     caf_info 
967         | or [ mayHaveCafRefs (hasCafRefs this_pkg subst1 (idArity bndr) rhs)
968              | (bndr,rhs) <- prs ] = MayHaveCafRefs
969         | otherwise                = NoCafRefs
970
971 -----------------------------------------------------------
972 tidyTopPair :: Bool  -- show unfolding
973             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
974                         -- It is knot-tied: don't look at it!
975             -> CafInfo
976             -> Name             -- New name
977             -> (Id, CoreExpr)   -- Binder and RHS before tidying
978             -> (Id, CoreExpr)
979         -- This function is the heart of Step 2
980         -- The rec_tidy_env is the one to use for the IdInfo
981         -- It's necessary because when we are dealing with a recursive
982         -- group, a variable late in the group might be mentioned
983         -- in the IdInfo of one early in the group
984
985 tidyTopPair show_unfold rhs_tidy_env caf_info name' (bndr, rhs)
986   = (bndr1, rhs1)
987   where
988     bndr1    = mkGlobalId details name' ty' idinfo'
989     details  = idDetails bndr   -- Preserve the IdDetails
990     ty'      = tidyTopType (idType bndr)
991     rhs1     = tidyExpr rhs_tidy_env rhs
992     idinfo'  = tidyTopIdInfo rhs_tidy_env name' rhs rhs1 (idInfo bndr) 
993                              show_unfold caf_info
994
995 -- tidyTopIdInfo creates the final IdInfo for top-level
996 -- binders.  There are two delicate pieces:
997 --
998 --  * Arity.  After CoreTidy, this arity must not change any more.
999 --      Indeed, CorePrep must eta expand where necessary to make
1000 --      the manifest arity equal to the claimed arity.
1001 --
1002 --  * CAF info.  This must also remain valid through to code generation.
1003 --      We add the info here so that it propagates to all
1004 --      occurrences of the binders in RHSs, and hence to occurrences in
1005 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
1006 --      CoreToStg makes use of this when constructing SRTs.
1007 tidyTopIdInfo :: TidyEnv -> Name -> CoreExpr -> CoreExpr 
1008               -> IdInfo -> Bool -> CafInfo -> IdInfo
1009 tidyTopIdInfo rhs_tidy_env name orig_rhs tidy_rhs idinfo show_unfold caf_info
1010   | not is_external     -- For internal Ids (not externally visible)
1011   = vanillaIdInfo       -- we only need enough info for code generation
1012                         -- Arity and strictness info are enough;
1013                         --      c.f. CoreTidy.tidyLetBndr
1014         `setCafInfo`        caf_info
1015         `setArityInfo`      arity
1016         `setStrictnessInfo` final_sig
1017
1018   | otherwise           -- Externally-visible Ids get the whole lot
1019   = vanillaIdInfo
1020         `setCafInfo`           caf_info
1021         `setArityInfo`         arity
1022         `setStrictnessInfo`    final_sig
1023         `setOccInfo`           robust_occ_info
1024         `setInlinePragInfo`    (inlinePragInfo idinfo)
1025         `setUnfoldingInfo`     unfold_info
1026                 -- NB: we throw away the Rules
1027                 -- They have already been extracted by findExternalRules
1028   where
1029     is_external = isExternalName name
1030
1031     --------- OccInfo ------------
1032     robust_occ_info = zapFragileOcc (occInfo idinfo)
1033     -- It's important to keep loop-breaker information
1034     -- when we are doing -fexpose-all-unfoldings
1035
1036     --------- Strictness ------------
1037     final_sig | Just sig <- strictnessInfo idinfo
1038               = WARN( _bottom_hidden sig, ppr name ) Just sig
1039               | Just (_, sig) <- mb_bot_str = Just sig
1040               | otherwise                   = Nothing
1041
1042     -- If the cheap-and-cheerful bottom analyser can see that
1043     -- the RHS is bottom, it should jolly well be exposed
1044     _bottom_hidden id_sig = case mb_bot_str of
1045                                Nothing         -> False
1046                                Just (arity, _) -> not (appIsBottom id_sig arity)
1047
1048     mb_bot_str = exprBotStrictness_maybe orig_rhs
1049
1050     --------- Unfolding ------------
1051     unf_info = unfoldingInfo idinfo
1052     unfold_info | show_unfold = tidyUnfolding rhs_tidy_env tidy_rhs final_sig unf_info
1053                 | otherwise   = noUnfolding
1054     -- NB: do *not* expose the worker if show_unfold is off,
1055     --     because that means this thing is a loop breaker or
1056     --     marked NOINLINE or something like that
1057     -- This is important: if you expose the worker for a loop-breaker
1058     -- then you can make the simplifier go into an infinite loop, because
1059     -- in effect the unfolding is exposed.  See Trac #1709
1060     -- 
1061     -- You might think that if show_unfold is False, then the thing should
1062     -- not be w/w'd in the first place.  But a legitimate reason is this:
1063     --    the function returns bottom
1064     -- In this case, show_unfold will be false (we don't expose unfoldings
1065     -- for bottoming functions), but we might still have a worker/wrapper
1066     -- split (see Note [Worker-wrapper for bottoming functions] in WorkWrap.lhs
1067
1068     --------- Arity ------------
1069     -- Usually the Id will have an accurate arity on it, because
1070     -- the simplifier has just run, but not always. 
1071     -- One case I found was when the last thing the simplifier
1072     -- did was to let-bind a non-atomic argument and then float
1073     -- it to the top level. So it seems more robust just to
1074     -- fix it here.
1075     arity = exprArity orig_rhs
1076
1077
1078
1079 ------------ Unfolding  --------------
1080 tidyUnfolding :: TidyEnv -> CoreExpr -> Maybe StrictSig -> Unfolding -> Unfolding
1081 tidyUnfolding tidy_env _ _ (DFunUnfolding con ids)
1082   = DFunUnfolding con (map (tidyExpr tidy_env) ids)
1083 tidyUnfolding tidy_env tidy_rhs strict_sig
1084               unf@(CoreUnfolding { uf_tmpl = unf_rhs, uf_src = src })
1085   | isInlineRuleSource src
1086   = unf { uf_tmpl = tidyExpr tidy_env unf_rhs,     -- Preserves OccInfo
1087           uf_src  = tidyInl tidy_env src }
1088   | otherwise
1089   = mkTopUnfolding is_bot tidy_rhs
1090   where
1091     is_bot = case strict_sig of 
1092                 Just sig -> isBottomingSig sig
1093                 Nothing  -> False
1094
1095 tidyUnfolding _ _ _ unf = unf
1096
1097 tidyInl :: TidyEnv -> UnfoldingSource -> UnfoldingSource
1098 tidyInl tidy_env (InlineWrapper w) = InlineWrapper (tidyVarOcc tidy_env w)
1099 tidyInl _        inl_info          = inl_info
1100 \end{code}
1101
1102 %************************************************************************
1103 %*                                                                      *
1104 \subsection{Figuring out CafInfo for an expression}
1105 %*                                                                      *
1106 %************************************************************************
1107
1108 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
1109 We mark such things as `MayHaveCafRefs' because this information is
1110 used to decide whether a particular closure needs to be referenced
1111 in an SRT or not.
1112
1113 There are two reasons for setting MayHaveCafRefs:
1114         a) The RHS is a CAF: a top-level updatable thunk.
1115         b) The RHS refers to something that MayHaveCafRefs
1116
1117 Possible improvement: In an effort to keep the number of CAFs (and 
1118 hence the size of the SRTs) down, we could also look at the expression and 
1119 decide whether it requires a small bounded amount of heap, so we can ignore 
1120 it as a CAF.  In these cases however, we would need to use an additional
1121 CAF list to keep track of non-collectable CAFs.  
1122
1123 \begin{code}
1124 hasCafRefs  :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
1125 hasCafRefs this_pkg p arity expr 
1126   | is_caf || mentions_cafs 
1127                             = MayHaveCafRefs
1128   | otherwise               = NoCafRefs
1129  where
1130   mentions_cafs = isFastTrue (cafRefs p expr)
1131   is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
1132
1133   -- NB. we pass in the arity of the expression, which is expected
1134   -- to be calculated by exprArity.  This is because exprArity
1135   -- knows how much eta expansion is going to be done by 
1136   -- CorePrep later on, and we don't want to duplicate that
1137   -- knowledge in rhsIsStatic below.
1138
1139 cafRefs :: VarEnv Id -> Expr a -> FastBool
1140 cafRefs p (Var id)
1141         -- imported Ids first:
1142   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
1143         -- now Ids local to this module:
1144   | otherwise =
1145      case lookupVarEnv p id of
1146         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
1147         Nothing  -> fastBool False
1148
1149 cafRefs _ (Lit _)              = fastBool False
1150 cafRefs p (App f a)            = fastOr (cafRefs p f) (cafRefs p) a
1151 cafRefs p (Lam _ e)            = cafRefs p e
1152 cafRefs p (Let b e)            = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
1153 cafRefs p (Case e _bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
1154 cafRefs p (Note _n e)          = cafRefs p e
1155 cafRefs p (Cast e _co)         = cafRefs p e
1156 cafRefs _ (Type _)             = fastBool False
1157
1158 cafRefss :: VarEnv Id -> [Expr a] -> FastBool
1159 cafRefss _ []     = fastBool False
1160 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
1161
1162 fastOr :: FastBool -> (a -> FastBool) -> a -> FastBool
1163 -- hack for lazy-or over FastBool.
1164 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
1165 \end{code}