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