Inject implicit bindings after CoreTidy, not before Simplify
[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, tidyProgram ) where
8
9 #include "HsVersions.h"
10
11 import TcRnTypes
12 import FamInstEnv
13 import DynFlags
14 import CoreSyn
15 import CoreUnfold
16 import CoreFVs
17 import CoreTidy
18 import PprCore
19 import CoreLint
20 import CoreUtils
21 import VarEnv
22 import VarSet
23 import Var
24 import Id
25 import Class
26 import IdInfo
27 import InstEnv
28 import NewDemand
29 import BasicTypes
30 import Name
31 import NameSet
32 import IfaceEnv
33 import NameEnv
34 import OccName
35 import TcType
36 import DataCon
37 import TyCon
38 import Module
39 import HscTypes
40 import Maybes
41 import ErrUtils
42 import UniqSupply
43 import Outputable
44 import FastBool hiding ( fastOr )
45
46 import Data.List        ( partition )
47 import Data.Maybe       ( isJust )
48 import Data.IORef       ( IORef, readIORef, writeIORef )
49 \end{code}
50
51
52 Constructing the TypeEnv, Instances, Rules from which the ModIface is
53 constructed, and which goes on to subsequent modules in --make mode.
54
55 Most of the interface file is obtained simply by serialising the
56 TypeEnv.  One important consequence is that if the *interface file*
57 has pragma info if and only if the final TypeEnv does. This is not so
58 important for *this* module, but it's essential for ghc --make:
59 subsequent compilations must not see (e.g.) the arity if the interface
60 file does not contain arity If they do, they'll exploit the arity;
61 then the arity might change, but the iface file doesn't change =>
62 recompilation does not happen => disaster. 
63
64 For data types, the final TypeEnv will have a TyThing for the TyCon,
65 plus one for each DataCon; the interface file will contain just one
66 data type declaration, but it is de-serialised back into a collection
67 of TyThings.
68
69 %************************************************************************
70 %*                                                                      *
71                 Plan A: simpleTidyPgm
72 %*                                                                      * 
73 %************************************************************************
74
75
76 Plan A: mkBootModDetails: omit pragmas, make interfaces small
77 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
78 * Ignore the bindings
79
80 * Drop all WiredIn things from the TypeEnv 
81         (we never want them in interface files)
82
83 * Retain all TyCons and Classes in the TypeEnv, to avoid
84         having to find which ones are mentioned in the
85         types of exported Ids
86
87 * Trim off the constructors of non-exported TyCons, both
88         from the TyCon and from the TypeEnv
89
90 * Drop non-exported Ids from the TypeEnv
91
92 * Tidy the types of the DFunIds of Instances, 
93   make them into GlobalIds, (they already have External Names)
94   and add them to the TypeEnv
95
96 * Tidy the types of the (exported) Ids in the TypeEnv,
97   make them into GlobalIds (they already have External Names)
98
99 * Drop rules altogether
100
101 * Tidy the bindings, to ensure that the Caf and Arity
102   information is correct for each top-level binder; the 
103   code generator needs it. And to ensure that local names have
104   distinct OccNames in case of object-file splitting
105
106 \begin{code}
107 -- This is Plan A: make a small type env when typechecking only,
108 -- or when compiling a hs-boot file, or simply when not using -O
109 --
110 -- We don't look at the bindings at all -- there aren't any
111 -- for hs-boot files
112
113 mkBootModDetailsTc :: HscEnv -> TcGblEnv -> IO ModDetails
114 mkBootModDetailsTc hsc_env 
115         TcGblEnv{ tcg_exports   = exports,
116                   tcg_type_env  = type_env,
117                   tcg_insts     = insts,
118                   tcg_fam_insts = fam_insts
119                 }
120   = mkBootModDetails hsc_env exports type_env insts fam_insts
121
122 mkBootModDetailsDs :: HscEnv -> ModGuts -> IO ModDetails
123 mkBootModDetailsDs hsc_env 
124         ModGuts{ mg_exports   = exports,
125                  mg_types     = type_env,
126                  mg_insts     = insts,
127                  mg_fam_insts = fam_insts
128                 }
129   = mkBootModDetails hsc_env exports type_env insts fam_insts
130   
131 mkBootModDetails :: HscEnv -> [AvailInfo] -> NameEnv TyThing
132                  -> [Instance] -> [FamInstEnv.FamInst] -> IO ModDetails
133 mkBootModDetails hsc_env exports type_env insts fam_insts
134   = do  { let dflags = hsc_dflags hsc_env 
135         ; showPass dflags "Tidy [hoot] type env"
136
137         ; let { insts'     = tidyInstances tidyExternalId insts
138               ; dfun_ids   = map instanceDFunId insts'
139               ; type_env1  = tidyBootTypeEnv (availsToNameSet exports) type_env
140               ; type_env'  = extendTypeEnvWithIds type_env1 dfun_ids
141               }
142         ; return (ModDetails { md_types     = type_env'
143                              , md_insts     = insts'
144                              , md_fam_insts = fam_insts
145                              , md_rules     = []
146                              , md_anns      = []
147                              , md_exports   = exports
148                              , md_vect_info = noVectInfo
149                              })
150         }
151   where
152
153 tidyBootTypeEnv :: NameSet -> TypeEnv -> TypeEnv
154 tidyBootTypeEnv exports type_env 
155   = tidyTypeEnv True False exports type_env final_ids
156   where
157         -- Find the LocalIds in the type env that are exported
158         -- Make them into GlobalIds, and tidy their types
159         --
160         -- It's very important to remove the non-exported ones
161         -- because we don't tidy the OccNames, and if we don't remove
162         -- the non-exported ones we'll get many things with the
163         -- same name in the interface file, giving chaos.
164     final_ids = [ tidyExternalId id
165                 | id <- typeEnvIds type_env
166                 , isLocalId id
167                 , keep_it id ]
168
169         -- default methods have their export flag set, but everything
170         -- else doesn't (yet), because this is pre-desugaring, so we
171         -- must test both.
172     keep_it id = isExportedId id || idName id `elemNameSet` exports
173
174
175 tidyExternalId :: Id -> Id
176 -- Takes an LocalId with an External Name, 
177 -- makes it into a GlobalId with VanillaIdInfo, and tidies its type
178 -- (NB: vanillaIdInfo makes a conservative assumption about Caf-hood.)
179 tidyExternalId id 
180   = ASSERT2( isLocalId id && isExternalName (idName id), ppr id )
181     mkVanillaGlobal (idName id) (tidyTopType (idType id))
182 \end{code}
183
184
185 %************************************************************************
186 %*                                                                      *
187         Plan B: tidy bindings, make TypeEnv full of IdInfo
188 %*                                                                      * 
189 %************************************************************************
190
191 Plan B: include pragmas, make interfaces 
192 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
193 * Figure out which Ids are externally visible
194
195 * Tidy the bindings, externalising appropriate Ids
196
197 * Drop all Ids from the TypeEnv, and add all the External Ids from 
198   the bindings.  (This adds their IdInfo to the TypeEnv; and adds
199   floated-out Ids that weren't even in the TypeEnv before.)
200
201 Step 1: Figure out external Ids
202 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
203 First we figure out which Ids are "external" Ids.  An
204 "external" Id is one that is visible from outside the compilation
205 unit.  These are
206         a) the user exported ones
207         b) ones mentioned in the unfoldings, workers, 
208            or rules of externally-visible ones 
209 This exercise takes a sweep of the bindings bottom to top.  Actually,
210 in Step 2 we're also going to need to know which Ids should be
211 exported with their unfoldings, so we produce not an IdSet but an
212 ExtIdEnv = IdEnv Bool
213
214
215 Step 2: Tidy the program
216 ~~~~~~~~~~~~~~~~~~~~~~~~
217 Next we traverse the bindings top to bottom.  For each *top-level*
218 binder
219
220  1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal, 
221     reflecting the fact that from now on we regard it as a global, 
222     not local, Id
223
224  2. Give it a system-wide Unique.
225     [Even non-exported things need system-wide Uniques because the
226     byte-code generator builds a single Name->BCO symbol table.]
227
228     We use the NameCache kept in the HscEnv as the
229     source of such system-wide uniques.
230
231     For external Ids, use the original-name cache in the NameCache
232     to ensure that the unique assigned is the same as the Id had 
233     in any previous compilation run.
234   
235  3. If it's an external Id, make it have a External Name, otherwise
236     make it have an Internal Name.
237     This is used by the code generator to decide whether
238     to make the label externally visible
239
240  4. Give external Ids a "tidy" OccName.  This means
241     we can print them in interface files without confusing 
242     "x" (unique 5) with "x" (unique 10).
243   
244  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
245         * its unfolding, if it should have one
246         
247         * its arity, computed from the number of visible lambdas
248
249         * its CAF info, computed from what is free in its RHS
250
251                 
252 Finally, substitute these new top-level binders consistently
253 throughout, including in unfoldings.  We also tidy binders in
254 RHSs, so that they print nicely in interfaces.
255
256 \begin{code}
257 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
258 tidyProgram hsc_env  (ModGuts { mg_module = mod, mg_exports = exports, 
259                                 mg_types = type_env, 
260                                 mg_insts = insts, mg_fam_insts = fam_insts,
261                                 mg_binds = binds, 
262                                 mg_rules = imp_rules,
263                                 mg_vect_info = vect_info,
264                                 mg_dir_imps = dir_imps, 
265                                 mg_anns = anns,
266                                 mg_deps = deps, 
267                                 mg_foreign = foreign_stubs,
268                                 mg_hpc_info = hpc_info,
269                                 mg_modBreaks = modBreaks })
270
271   = do  { let dflags = hsc_dflags hsc_env
272         ; showPass dflags "Tidy Core"
273
274         ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
275               ; th         = dopt Opt_TemplateHaskell      dflags
276               ; ext_ids = findExternalIds omit_prags binds
277               ; ext_rules 
278                    | omit_prags = []
279                    | otherwise  = findExternalRules binds imp_rules ext_ids
280                 -- findExternalRules filters imp_rules to avoid binders that 
281                 -- aren't externally visible; but the externally-visible binders 
282                 -- are computed (by findExternalIds) assuming that all orphan
283                 -- rules are exported (they get their Exported flag set in the desugarer)
284                 -- So in fact we may export more than we need. 
285                 -- (It's a sort of mutual recursion.)
286         }
287
288         ; (tidy_env, tidy_binds) <- tidyTopBinds hsc_env mod type_env ext_ids 
289                                                  binds
290
291         ; let { export_set = availsToNameSet exports
292               ; final_ids  = [ id | id <- bindersOfBinds tidy_binds, 
293                                     isExternalName (idName id)]
294               ; tidy_type_env = tidyTypeEnv omit_prags th export_set
295                                             type_env final_ids
296               ; tidy_insts    = tidyInstances (lookup_dfun tidy_type_env) insts
297                 -- A DFunId will have a binding in tidy_binds, and so
298                 -- will now be in final_env, replete with IdInfo
299                 -- Its name will be unchanged since it was born, but
300                 -- we want Global, IdInfo-rich (or not) DFunId in the
301                 -- tidy_insts
302
303               ; tidy_rules = tidyRules tidy_env ext_rules
304                 -- You might worry that the tidy_env contains IdInfo-rich stuff
305                 -- and indeed it does, but if omit_prags is on, ext_rules is
306                 -- empty
307
308               -- See Note [Injecting implicit bindings]
309               ; implicit_binds = getImplicitBinds type_env
310               ; all_tidy_binds = implicit_binds ++ tidy_binds
311
312               ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
313               }
314
315         ; endPass dflags "Tidy Core" Opt_D_dump_simpl all_tidy_binds
316         ; dumpIfSet_core dflags Opt_D_dump_simpl
317                 "Tidy Core Rules"
318                 (pprRules tidy_rules)
319
320         ; let dir_imp_mods = moduleEnvKeys dir_imps
321
322         ; return (CgGuts { cg_module   = mod, 
323                            cg_tycons   = alg_tycons,
324                            cg_binds    = all_tidy_binds,
325                            cg_dir_imps = dir_imp_mods,
326                            cg_foreign  = foreign_stubs,
327                            cg_dep_pkgs = dep_pkgs deps,
328                            cg_hpc_info = hpc_info,
329                            cg_modBreaks = modBreaks }, 
330
331                    ModDetails { md_types     = tidy_type_env,
332                                 md_rules     = tidy_rules,
333                                 md_insts     = tidy_insts,
334                                 md_fam_insts = fam_insts,
335                                 md_exports   = exports,
336                                 md_anns      = anns,     -- are already tidy
337                                 md_vect_info = vect_info --
338                               })
339         }
340
341 lookup_dfun :: TypeEnv -> Var -> Id
342 lookup_dfun type_env dfun_id
343   = case lookupTypeEnv type_env (idName dfun_id) of
344         Just (AnId dfun_id') -> dfun_id'
345         _other -> pprPanic "lookup_dfun" (ppr dfun_id)
346
347 --------------------------
348 tidyTypeEnv :: Bool     -- Compiling without -O, so omit prags
349             -> Bool     -- Template Haskell is on
350             -> NameSet -> TypeEnv -> [Id] -> TypeEnv
351
352 -- The competed type environment is gotten from
353 --      Dropping any wired-in things, and then
354 --      a) keeping the types and classes
355 --      b) removing all Ids, 
356 --      c) adding Ids with correct IdInfo, including unfoldings,
357 --              gotten from the bindings
358 -- From (c) we keep only those Ids with External names;
359 --          the CoreTidy pass makes sure these are all and only
360 --          the externally-accessible ones
361 -- This truncates the type environment to include only the 
362 -- exported Ids and things needed from them, which saves space
363
364 tidyTypeEnv omit_prags th exports type_env final_ids
365  = let  type_env1 = filterNameEnv keep_it type_env
366         type_env2 = extendTypeEnvWithIds type_env1 final_ids
367         type_env3 | omit_prags = mapNameEnv (trimThing th exports) type_env2
368                   | otherwise  = type_env2
369     in 
370     type_env3
371   where
372         -- We keep GlobalIds, because they won't appear 
373         -- in the bindings from which final_ids are derived!
374         -- (The bindings bind LocalIds.)
375     keep_it thing | isWiredInThing thing = False
376     keep_it (AnId id) = isGlobalId id   -- Keep GlobalIds (e.g. class ops)
377     keep_it _other    = True            -- Keep all TyCons, DataCons, and Classes
378
379 --------------------------
380 isWiredInThing :: TyThing -> Bool
381 isWiredInThing thing = isWiredInName (getName thing)
382
383 --------------------------
384 trimThing :: Bool -> NameSet -> TyThing -> TyThing
385 -- Trim off inessentials, for boot files and no -O
386 trimThing th exports (ATyCon tc)
387    | not th && not (mustExposeTyCon exports tc)
388    = ATyCon (makeTyConAbstract tc)      -- Note [Trimming and Template Haskell]
389
390 trimThing _th _exports (AnId id)
391    | not (isImplicitId id) 
392    = AnId (id `setIdInfo` vanillaIdInfo)
393
394 trimThing _th _exports other_thing 
395   = other_thing
396
397
398 {- Note [Trimming and Template Haskell]
399    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
400 Consider (Trac #2386) this
401         module M(T, makeOne) where
402           data T = Yay String
403           makeOne = [| Yay "Yep" |]
404 Notice that T is exported abstractly, but makeOne effectively exports it too!
405 A module that splices in $(makeOne) will then look for a declartion of Yay,
406 so it'd better be there.  Hence, brutally but simply, we switch off type
407 constructor trimming if TH is enabled in this module. -}
408
409
410 mustExposeTyCon :: NameSet      -- Exports
411                 -> TyCon        -- The tycon
412                 -> Bool         -- Can its rep be hidden?
413 -- We are compiling without -O, and thus trying to write as little as 
414 -- possible into the interface file.  But we must expose the details of
415 -- any data types whose constructors or fields are exported
416 mustExposeTyCon exports tc
417   | not (isAlgTyCon tc)         -- Synonyms
418   = True
419   | isEnumerationTyCon tc       -- For an enumeration, exposing the constructors
420   = True                        -- won't lead to the need for further exposure
421                                 -- (This includes data types with no constructors.)
422   | isOpenTyCon tc              -- Open type family
423   = True
424
425   | otherwise                   -- Newtype, datatype
426   = any exported_con (tyConDataCons tc)
427         -- Expose rep if any datacon or field is exported
428
429   || (isNewTyCon tc && isFFITy (snd (newTyConRhs tc)))
430         -- Expose the rep for newtypes if the rep is an FFI type.  
431         -- For a very annoying reason.  'Foreign import' is meant to
432         -- be able to look through newtypes transparently, but it
433         -- can only do that if it can "see" the newtype representation
434   where
435     exported_con con = any (`elemNameSet` exports) 
436                            (dataConName con : dataConFieldLabels con)
437
438 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
439 tidyInstances tidy_dfun ispecs
440   = map tidy ispecs
441   where
442     tidy ispec = setInstanceDFunId ispec $
443                  tidy_dfun (instanceDFunId ispec)
444 \end{code}
445
446
447 %************************************************************************
448 %*                                                                      *
449         Implicit bindings
450 %*                                                                      *
451 %************************************************************************
452
453 Note [Injecting implicit bindings]
454 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
455 We inject the implict bindings right at the end, in CoreTidy.
456 Some of these bindings, notably record selectors, are not
457 constructed in an optimised form.  E.g. record selector for
458         data T = MkT { x :: {-# UNPACK #-} !Int }
459 Then the unfolding looks like
460         x = \t. case t of MkT x1 -> let x = I# x1 in x
461 This generates bad code unless it's first simplified a bit.  That is
462 why CoreUnfold.mkImplicitUnfolding uses simleExprOpt to do a bit of
463 optimisation first.  (Only matters when the selector is used curried;
464 eg map x ys.)  See Trac #2070.
465
466 At one time I tried injecting the implicit bindings *early*, at the
467 beginning of SimplCore.  But that gave rise to real difficulty,
468 becuase GlobalIds are supposed to have *fixed* IdInfo, but the
469 simplifier and other core-to-core passes mess with IdInfo all the
470 time.  The straw that broke the camels back was when a class selector
471 got the wrong arity -- ie the simplifier gave it arity 2, whereas
472 importing modules were expecting it to have arity 1 (Trac #2844).
473 It's much safer just to inject them right at the end, after tidying.
474
475
476 \begin{code}
477 getImplicitBinds :: TypeEnv -> [CoreBind]
478 getImplicitBinds type_env
479   = map get_defn (concatMap implicit_con_ids (typeEnvTyCons type_env)
480                   ++ concatMap other_implicit_ids (typeEnvElts type_env))
481         -- Put the constructor wrappers first, because
482         -- other implicit bindings (notably the fromT functions arising 
483         -- from generics) use the constructor wrappers.  At least that's
484         -- what External Core likes
485   where
486     implicit_con_ids tc = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
487     
488     other_implicit_ids (ATyCon tc) = filter (not . isNaughtyRecordSelector) (tyConSelIds tc)
489         -- The "naughty" ones are not real functions at all
490         -- They are there just so we can get decent error messages
491         -- See Note  [Naughty record selectors] in MkId.lhs
492     other_implicit_ids (AClass cl) = classSelIds cl
493     other_implicit_ids _other      = []
494     
495     get_defn :: Id -> CoreBind
496     get_defn id = NonRec id (unfoldingTemplate (idUnfolding id))
497 \end{code}
498
499
500 %************************************************************************
501 %*                                                                      *
502 \subsection{Step 1: finding externals}
503 %*                                                                      * 
504 %************************************************************************
505
506 \begin{code}
507 type ExtIdEnv = IdEnv Bool      
508         -- In domain => Id is external
509         -- Range = True <=> show unfolding, 
510                 -- Always True for InlineRule 
511
512 findExternalIds :: Bool -> [CoreBind] -> ExtIdEnv
513         -- Step 1 from the notes above
514 findExternalIds omit_prags binds
515   | omit_prags
516   = mkVarEnv [ (id,False) | id <- bindersOfBinds binds, isExportedId id ]
517
518   | otherwise
519   = foldr find emptyVarEnv binds
520   where
521     find (NonRec id rhs) needed
522         | need_id needed id = addExternal (id,rhs) needed
523         | otherwise         = needed
524     find (Rec prs) needed   = find_prs prs needed
525
526         -- For a recursive group we have to look for a fixed point
527     find_prs prs needed 
528         | null needed_prs = needed
529         | otherwise       = find_prs other_prs new_needed
530         where
531           (needed_prs, other_prs) = partition (need_pr needed) prs
532           new_needed = foldr addExternal needed needed_prs
533
534         -- The 'needed' set contains the Ids that are needed by earlier
535         -- interface file emissions.  If the Id isn't in this set, and isn't
536         -- exported, there's no need to emit anything
537     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
538     need_pr needed_set (id,_)   = need_id needed_set id
539
540 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
541 -- The Id is needed; extend the needed set
542 -- with it and its dependents (free vars etc)
543 addExternal (id,rhs) needed
544   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
545                  id show_unfold
546   where
547     add_occ id needed | id `elemVarEnv` needed = needed
548                       | otherwise              = extendVarEnv needed id False
549         -- "False" because we don't know we need the Id's unfolding
550         -- Don't override existing bindings; we might have already set it to True
551
552     new_needed_ids = (mb_unfold_ids `orElse` emptyVarSet) `unionVarSet`
553                      spec_ids
554
555     idinfo         = idInfo id
556     dont_inline    = isNeverActive (inlinePragInfo idinfo)
557     loop_breaker   = isNonRuleLoopBreaker (occInfo idinfo)
558     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
559     spec_ids       = specInfoFreeVars (specInfo idinfo)
560
561         -- Stuff to do with the Id's unfolding
562         -- We leave the unfolding there even if there is a worker
563         -- In GHCI the unfolding is used by importers
564     show_unfold = isJust mb_unfold_ids
565
566     mb_unfold_ids :: Maybe IdSet        -- Nothing => don't unfold
567     mb_unfold_ids = case unfoldingInfo idinfo of
568                       InlineRule { uf_worker = Just wkr_id } -> Just (unitVarSet wkr_id)
569                       InlineRule { uf_tmpl = rhs }           -> Just (exprFreeIds rhs)
570                       CoreUnfolding { uf_guidance = guide } 
571                         | not bottoming_fn              -- Not necessary
572                         , not dont_inline        
573                         , not loop_breaker       
574                         , not (neverUnfoldGuidance guide)
575                         -> Just (exprFreeIds rhs)       -- The simplifier has put an up-to-date unfolding
576                                                         -- in the IdInfo, but the RHS will do just as well
577                     
578                       _ -> Nothing
579 \end{code}
580
581
582 \begin{code}
583 findExternalRules :: [CoreBind]
584                   -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
585                   -> IdEnv a    -- Ids that are exported, so we need their rules
586                   -> [CoreRule]
587   -- The complete rules are gotten by combining
588   --    a) the non-local rules
589   --    b) rules embedded in the top-level Ids
590 findExternalRules binds non_local_rules ext_ids
591   = filter (not . internal_rule) (non_local_rules ++ local_rules)
592   where
593     local_rules  = [ rule
594                    | id <- bindersOfBinds binds,
595                      id `elemVarEnv` ext_ids,
596                      rule <- idCoreRules id
597                    ]
598
599     internal_rule rule
600         =  any internal_id (varSetElems (ruleLhsFreeIds rule))
601                 -- Don't export a rule whose LHS mentions a locally-defined
602                 --  Id that is completely internal (i.e. not visible to an
603                 -- importing module)
604
605     internal_id id = not (id `elemVarEnv` ext_ids)
606 \end{code}
607
608
609
610 %************************************************************************
611 %*                                                                      *
612 \subsection{Step 2: top-level tidying}
613 %*                                                                      *
614 %************************************************************************
615
616
617 \begin{code}
618 -- TopTidyEnv: when tidying we need to know
619 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
620 --        These may have arisen because the
621 --        renamer read in an interface file mentioning M.$wf, say,
622 --        and assigned it unique r77.  If, on this compilation, we've
623 --        invented an Id whose name is $wf (but with a different unique)
624 --        we want to rename it to have unique r77, so that we can do easy
625 --        comparisons with stuff from the interface file
626 --
627 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
628 --     are 'used'
629 --
630 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
631
632 tidyTopBinds :: HscEnv
633              -> Module
634              -> TypeEnv
635              -> ExtIdEnv
636              -> [CoreBind]
637              -> IO (TidyEnv, [CoreBind])
638
639 tidyTopBinds hsc_env mod type_env ext_ids binds
640   = tidy init_env binds
641   where
642     nc_var = hsc_NC hsc_env 
643
644         -- We also make sure to avoid any exported binders.  Consider
645         --      f{-u1-} = 1     -- Local decl
646         --      ...
647         --      f{-u2-} = 2     -- Exported decl
648         --
649         -- The second exported decl must 'get' the name 'f', so we
650         -- have to put 'f' in the avoids list before we get to the first
651         -- decl.  tidyTopId then does a no-op on exported binders.
652     init_env = (initTidyOccEnv avoids, emptyVarEnv)
653     avoids   = [getOccName name | bndr <- typeEnvIds type_env,
654                                   let name = idName bndr,
655                                   isExternalName name]
656                 -- In computing our "avoids" list, we must include
657                 --      all implicit Ids
658                 --      all things with global names (assigned once and for
659                 --                                      all by the renamer)
660                 -- since their names are "taken".
661                 -- The type environment is a convenient source of such things.
662
663     this_pkg = thisPackage (hsc_dflags hsc_env)
664
665     tidy env []     = return (env, [])
666     tidy env (b:bs) = do { (env1, b')  <- tidyTopBind this_pkg mod nc_var ext_ids env b
667                          ; (env2, bs') <- tidy env1 bs
668                          ; return (env2, b':bs') }
669
670 ------------------------
671 tidyTopBind  :: PackageId
672              -> Module
673              -> IORef NameCache -- For allocating new unique names
674              -> ExtIdEnv
675              -> TidyEnv -> CoreBind
676              -> IO (TidyEnv, CoreBind)
677
678 tidyTopBind this_pkg mod nc_var ext_ids (occ_env1,subst1) (NonRec bndr rhs)
679   = do  { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
680         ; let   { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
681                 ; subst2        = extendVarEnv subst1 bndr bndr'
682                 ; tidy_env2     = (occ_env2, subst2) }
683         ; return (tidy_env2, NonRec bndr' rhs') }
684   where
685     caf_info = hasCafRefs this_pkg subst1 (idArity bndr) rhs
686
687 tidyTopBind this_pkg mod nc_var ext_ids (occ_env1,subst1) (Rec prs)
688   = do  { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
689         ; let   { prs'      = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
690                                       names' prs
691                 ; subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
692                 ; tidy_env2 = (occ_env2, subst2) }
693         ; return (tidy_env2, Rec prs') }
694   where
695     bndrs = map fst prs
696
697         -- the CafInfo for a recursive group says whether *any* rhs in
698         -- the group may refer indirectly to a CAF (because then, they all do).
699     caf_info 
700         | or [ mayHaveCafRefs (hasCafRefs this_pkg subst1 (idArity bndr) rhs)
701              | (bndr,rhs) <- prs ] = MayHaveCafRefs
702         | otherwise                = NoCafRefs
703
704 --------------------------------------------------------------------
705 --              tidyTopName
706 -- This is where we set names to local/global based on whether they really are 
707 -- externally visible (see comment at the top of this module).  If the name
708 -- was previously local, we have to give it a unique occurrence name if
709 -- we intend to externalise it.
710 tidyTopNames :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
711              -> [Id] -> IO (TidyOccEnv, [Name])
712 tidyTopNames _mod _nc_var _ext_ids occ_env [] = return (occ_env, [])
713 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
714   = do  { (occ_env1, name)  <- tidyTopName  mod nc_var ext_ids occ_env id
715         ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
716         ; return (occ_env2, name:names) }
717
718 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
719             -> Id -> IO (TidyOccEnv, Name)
720 tidyTopName mod nc_var ext_ids occ_env id
721   | global && internal = return (occ_env, localiseName name)
722
723   | global && external = return (occ_env, name)
724         -- Global names are assumed to have been allocated by the renamer,
725         -- so they already have the "right" unique
726         -- And it's a system-wide unique too
727
728   -- Now we get to the real reason that all this is in the IO Monad:
729   -- we have to update the name cache in a nice atomic fashion
730
731   | local  && internal = do { nc <- readIORef nc_var
732                             ; let (nc', new_local_name) = mk_new_local nc
733                             ; writeIORef nc_var nc'
734                             ; return (occ_env', new_local_name) }
735         -- Even local, internal names must get a unique occurrence, because
736         -- if we do -split-objs we externalise the name later, in the code generator
737         --
738         -- Similarly, we must make sure it has a system-wide Unique, because
739         -- the byte-code generator builds a system-wide Name->BCO symbol table
740
741   | local  && external = do { nc <- readIORef nc_var
742                             ; let (nc', new_external_name) = mk_new_external nc
743                             ; writeIORef nc_var nc'
744                             ; return (occ_env', new_external_name) }
745
746   | otherwise = panic "tidyTopName"
747   where
748     name        = idName id
749     external    = id `elemVarEnv` ext_ids
750     global      = isExternalName name
751     local       = not global
752     internal    = not external
753     loc         = nameSrcSpan name
754
755     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
756
757     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
758                     where
759                       (us1, us2) = splitUniqSupply (nsUniqs nc)
760                       uniq       = uniqFromSupply us1
761
762     mk_new_external nc = allocateGlobalBinder nc mod occ' loc
763         -- If we want to externalise a currently-local name, check
764         -- whether we have already assigned a unique for it.
765         -- If so, use it; if not, extend the table.
766         -- All this is done by allcoateGlobalBinder.
767         -- This is needed when *re*-compiling a module in GHCi; we must
768         -- use the same name for externally-visible things as we did before.
769
770
771 -----------------------------------------------------------
772 tidyTopPair :: VarEnv Bool
773             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
774                         -- It is knot-tied: don't look at it!
775             -> CafInfo
776             -> Name             -- New name
777             -> (Id, CoreExpr)   -- Binder and RHS before tidying
778             -> (Id, CoreExpr)
779         -- This function is the heart of Step 2
780         -- The rec_tidy_env is the one to use for the IdInfo
781         -- It's necessary because when we are dealing with a recursive
782         -- group, a variable late in the group might be mentioned
783         -- in the IdInfo of one early in the group
784
785 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
786   = (bndr', rhs')
787   where
788     bndr' = mkGlobalId details name' ty' idinfo'
789         -- Preserve the GlobalIdDetails of existing global-ids
790     details = case globalIdDetails bndr of      
791                 NotGlobalId -> VanillaGlobal
792                 old_details -> old_details
793     ty'     = tidyTopType (idType bndr)
794     rhs'    = tidyExpr rhs_tidy_env rhs
795     idinfo  = idInfo bndr
796     idinfo' = tidyTopIdInfo (isJust maybe_external)
797                             idinfo unfold_info
798                             arity caf_info
799
800     -- Expose an unfolding if ext_ids tells us to
801     -- Remember that ext_ids maps an Id to a Bool: 
802     --  True to show the unfolding, False to hide it
803     maybe_external = lookupVarEnv ext_ids bndr
804     show_unfold = maybe_external `orElse` False
805     unfold_info | show_unfold = tidyUnfolding rhs_tidy_env rhs' (unfoldingInfo idinfo)
806                 | otherwise   = noUnfolding
807     -- NB: do *not* expose the worker if show_unfold is off,
808     --     because that means this thing is a loop breaker or
809     --     marked NOINLINE or something like that
810     -- This is important: if you expose the worker for a loop-breaker
811     -- then you can make the simplifier go into an infinite loop, because
812     -- in effect the unfolding is exposed.  See Trac #1709
813     -- 
814     -- You might think that if show_unfold is False, then the thing should
815     -- not be w/w'd in the first place.  But a legitimate reason is this:
816     --    the function returns bottom
817     -- In this case, show_unfold will be false (we don't expose unfoldings
818     -- for bottoming functions), but we might still have a worker/wrapper
819     -- split (see Note [Worker-wrapper for bottoming functions] in WorkWrap.lhs
820
821     -- Usually the Id will have an accurate arity on it, because
822     -- the simplifier has just run, but not always. 
823     -- One case I found was when the last thing the simplifier
824     -- did was to let-bind a non-atomic argument and then float
825     -- it to the top level. So it seems more robust just to
826     -- fix it here.
827     arity = exprArity rhs
828
829
830 -- tidyTopIdInfo creates the final IdInfo for top-level
831 -- binders.  There are two delicate pieces:
832 --
833 --  * Arity.  After CoreTidy, this arity must not change any more.
834 --      Indeed, CorePrep must eta expand where necessary to make
835 --      the manifest arity equal to the claimed arity.
836 --
837 --  * CAF info.  This must also remain valid through to code generation.
838 --      We add the info here so that it propagates to all
839 --      occurrences of the binders in RHSs, and hence to occurrences in
840 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
841 --      CoreToStg makes use of this when constructing SRTs.
842 tidyTopIdInfo :: Bool -> IdInfo -> Unfolding
843               -> ArityInfo -> CafInfo
844               -> IdInfo
845 tidyTopIdInfo is_external idinfo unfold_info arity caf_info
846   | not is_external     -- For internal Ids (not externally visible)
847   = vanillaIdInfo       -- we only need enough info for code generation
848                         -- Arity and strictness info are enough;
849                         --      c.f. CoreTidy.tidyLetBndr
850         `setCafInfo`           caf_info
851         `setArityInfo`         arity
852         `setAllStrictnessInfo` newStrictnessInfo idinfo
853
854   | otherwise           -- Externally-visible Ids get the whole lot
855   = vanillaIdInfo
856         `setCafInfo`           caf_info
857         `setArityInfo`         arity
858         `setAllStrictnessInfo` newStrictnessInfo idinfo
859         `setInlinePragInfo`    inlinePragInfo idinfo
860         `setUnfoldingInfo`     unfold_info
861                 -- NB: we throw away the Rules
862                 -- They have already been extracted by findExternalRules
863
864
865
866 ------------ Unfolding  --------------
867 tidyUnfolding :: TidyEnv -> CoreExpr -> Unfolding -> Unfolding
868 tidyUnfolding tidy_env _ unf@(InlineRule { uf_tmpl = rhs, uf_worker = mb_wkr })
869   = unf { uf_tmpl = tidyExpr tidy_env rhs, 
870           uf_worker = fmap (tidyVarOcc tidy_env) mb_wkr }
871 tidyUnfolding _ tidy_rhs (CoreUnfolding {})
872   = mkTopUnfolding tidy_rhs
873 tidyUnfolding _ _ unf = unf
874 \end{code}
875
876 %************************************************************************
877 %*                                                                      *
878 \subsection{Figuring out CafInfo for an expression}
879 %*                                                                      *
880 %************************************************************************
881
882 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
883 We mark such things as `MayHaveCafRefs' because this information is
884 used to decide whether a particular closure needs to be referenced
885 in an SRT or not.
886
887 There are two reasons for setting MayHaveCafRefs:
888         a) The RHS is a CAF: a top-level updatable thunk.
889         b) The RHS refers to something that MayHaveCafRefs
890
891 Possible improvement: In an effort to keep the number of CAFs (and 
892 hence the size of the SRTs) down, we could also look at the expression and 
893 decide whether it requires a small bounded amount of heap, so we can ignore 
894 it as a CAF.  In these cases however, we would need to use an additional
895 CAF list to keep track of non-collectable CAFs.  
896
897 \begin{code}
898 hasCafRefs  :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
899 hasCafRefs this_pkg p arity expr 
900   | is_caf || mentions_cafs 
901                             = MayHaveCafRefs
902   | otherwise               = NoCafRefs
903  where
904   mentions_cafs = isFastTrue (cafRefs p expr)
905   is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
906
907   -- NB. we pass in the arity of the expression, which is expected
908   -- to be calculated by exprArity.  This is because exprArity
909   -- knows how much eta expansion is going to be done by 
910   -- CorePrep later on, and we don't want to duplicate that
911   -- knowledge in rhsIsStatic below.
912
913 cafRefs :: VarEnv Id -> Expr a -> FastBool
914 cafRefs p (Var id)
915         -- imported Ids first:
916   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
917         -- now Ids local to this module:
918   | otherwise =
919      case lookupVarEnv p id of
920         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
921         Nothing  -> fastBool False
922
923 cafRefs _ (Lit _)              = fastBool False
924 cafRefs p (App f a)            = fastOr (cafRefs p f) (cafRefs p) a
925 cafRefs p (Lam _ e)            = cafRefs p e
926 cafRefs p (Let b e)            = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
927 cafRefs p (Case e _bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
928 cafRefs p (Note _n e)          = cafRefs p e
929 cafRefs p (Cast e _co)         = cafRefs p e
930 cafRefs _ (Type _)             = fastBool False
931
932 cafRefss :: VarEnv Id -> [Expr a] -> FastBool
933 cafRefss _ []     = fastBool False
934 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
935
936 fastOr :: FastBool -> (a -> FastBool) -> a -> FastBool
937 -- hack for lazy-or over FastBool.
938 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
939 \end{code}