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