e22cb001cb410e1c9e1177e17d6bbdb11b5a0231
[ghc-hetmet.git] / compiler / deSugar / DsBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsBinds]{Pattern-matching bindings (HsBinds and MonoBinds)}
5
6 Handles @HsBinds@; those at the top level require different handling,
7 in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
8 lower levels it is preserved with @let@/@letrec@s).
9
10 \begin{code}
11 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, 
12                  dsCoercion,
13                  AutoScc(..)
14   ) where
15
16 #include "HsVersions.h"
17
18
19 import {-# SOURCE #-}   DsExpr( dsLExpr, dsExpr )
20 import {-# SOURCE #-}   Match( matchWrapper )
21
22 import DsMonad
23 import DsGRHSs          ( dsGuarded )
24 import DsUtils
25
26 import HsSyn            -- lots of things
27 import CoreSyn          -- lots of things
28 import CoreUtils        ( exprType, mkInlineMe, mkSCC )
29
30 import StaticFlags      ( opt_AutoSccsOnAllToplevs,
31                           opt_AutoSccsOnExportedToplevs )
32 import OccurAnal        ( occurAnalyseExpr )
33 import CostCentre       ( mkAutoCC, IsCafCC(..) )
34 import Id               ( Id, DictId, idType, idName, isExportedId, mkLocalId, setInlinePragma )
35 import Rules            ( addIdSpecialisations, mkLocalRule )
36 import Var              ( TyVar, Var, isGlobalId, setIdNotExported )
37 import VarEnv
38 import Type             ( mkTyVarTy, substTyWith )
39 import TysWiredIn       ( voidTy )
40 import Outputable
41 import SrcLoc           ( Located(..) )
42 import Maybes           ( isJust, catMaybes, orElse )
43 import Bag              ( bagToList )
44 import BasicTypes       ( Activation(..), InlineSpec(..), isAlwaysActive )
45 import Monad            ( foldM )
46 import FastString       ( mkFastString )
47 import List             ( (\\) )
48 import Util             ( mapSnd )
49 \end{code}
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
54 %*                                                                      *
55 %************************************************************************
56
57 \begin{code}
58 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
59 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
60
61 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
62 dsLHsBinds binds = ds_lhs_binds NoSccs binds
63
64
65 ------------------------
66 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
67          -- scc annotation policy (see below)
68 ds_lhs_binds auto_scc binds =  foldM (dsLHsBind auto_scc) [] (bagToList binds)
69
70 dsLHsBind :: AutoScc
71          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
72          -> LHsBind Id
73          -> DsM [(Id,CoreExpr)] -- Result
74 dsLHsBind auto_scc rest (L loc bind)
75   = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
76
77 dsHsBind :: AutoScc
78          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
79          -> HsBind Id
80          -> DsM [(Id,CoreExpr)] -- Result
81
82 dsHsBind auto_scc rest (VarBind var expr)
83   = dsLExpr expr                `thenDs` \ core_expr ->
84
85         -- Dictionary bindings are always VarMonoBinds, so
86         -- we only need do this here
87     addDictScc var core_expr    `thenDs` \ core_expr' ->
88     returnDs ((var, core_expr') : rest)
89
90 dsHsBind auto_scc rest (FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn })
91   = matchWrapper (FunRhs (idName fun)) matches          `thenDs` \ (args, body) ->
92     dsCoercion co_fn (return (mkLams args body))        `thenDs` \ rhs ->
93     addAutoScc auto_scc (fun, rhs)                      `thenDs` \ pair ->
94     returnDs (pair : rest)
95
96 dsHsBind auto_scc rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty })
97   = dsGuarded grhss ty                          `thenDs` \ body_expr ->
98     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
99     mappM (addAutoScc auto_scc) sel_binds       `thenDs` \ sel_binds ->
100     returnDs (sel_binds ++ rest)
101
102 -- Note [Rules and inlining]
103 -- Common special case: no type or dictionary abstraction
104 -- This is a bit less trivial than you might suppose
105 -- The naive way woudl be to desguar to something like
106 --      f_lcl = ...f_lcl...     -- The "binds" from AbsBinds
107 --      M.f = f_lcl             -- Generated from "exports"
108 -- But we don't want that, because if M.f isn't exported,
109 -- it'll be inlined unconditionally at every call site (its rhs is 
110 -- trivial).  That woudl be ok unless it has RULES, which would 
111 -- thereby be completely lost.  Bad, bad, bad.
112 --
113 -- Instead we want to generate
114 --      M.f = ...f_lcl...
115 --      f_lcl = M.f
116 -- Now all is cool. The RULES are attached to M.f (by SimplCore), 
117 -- and f_lcl is rapidly inlined away.
118 --
119 -- This does not happen in the same way to polymorphic binds,
120 -- because they desugar to
121 --      M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
122 -- Although I'm a bit worried about whether full laziness might
123 -- float the f_lcl binding out and then inline M.f at its call site
124
125 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
126   = do  { core_prs <- ds_lhs_binds (addSccs auto_scc exports) binds
127         ; let env = mkVarEnv [ (lcl_id, (gbl_id, prags)) 
128                              | (_, gbl_id, lcl_id, prags) <- exports]
129               do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
130                                    = addInlinePrags prags gbl_id rhs
131                                    | otherwise = (lcl_id, rhs)
132               locals'  = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
133         ; return (map do_one core_prs ++ locals' ++ rest) }
134                 -- No Rec needed here (contrast the other AbsBinds cases)
135                 -- because we can rely on the enclosing dsBind to wrap in Rec
136
137         -- Another common case: one exported variable
138         -- Non-recursive bindings come through this way
139 dsHsBind auto_scc rest
140      (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
141   = ASSERT( all (`elem` tyvars) all_tyvars )
142     ds_lhs_binds (addSccs auto_scc exports) binds       `thenDs` \ core_prs ->
143     let 
144         -- Always treat the binds as recursive, because the typechecker
145         -- makes rather mixed-up dictionary bindings
146         core_bind = Rec core_prs
147     in
148     mappM (dsSpec all_tyvars dicts tyvars global local core_bind) 
149           prags                         `thenDs` \ mb_specs ->
150     let
151         (spec_binds, rules) = unzip (catMaybes mb_specs)
152         global' = addIdSpecialisations global rules
153         rhs'    = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
154     in
155     returnDs (addInlinePrags prags global' rhs' : spec_binds ++ rest)
156
157 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
158   = ds_lhs_binds (addSccs auto_scc exports) binds       `thenDs` \ core_prs ->
159      let 
160         add_inline (bndr,rhs) | Just prags <- lookupVarEnv inline_env bndr
161                               = addInlinePrags prags bndr rhs
162                               | otherwise = (bndr,rhs)
163         inline_env = mkVarEnv [(lcl_id, prags) | (_, _, lcl_id, prags) <- exports]
164                                            
165         -- Rec because of mixed-up dictionary bindings
166         core_bind = Rec (map add_inline core_prs)
167
168         tup_expr      = mkTupleExpr locals
169         tup_ty        = exprType tup_expr
170         poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
171                         Let core_bind tup_expr
172         locals        = [local | (_, _, local, _) <- exports]
173         local_tys     = map idType locals
174     in
175     newSysLocalDs (exprType poly_tup_expr)              `thenDs` \ poly_tup_id ->
176     let
177         dict_args = map Var dicts
178
179         mk_bind ((tyvars, global, local, prags), n)     -- locals !! n == local
180           =     -- Need to make fresh locals to bind in the selector, because
181                 -- some of the tyvars will be bound to voidTy
182             newSysLocalsDs (map substitute local_tys)   `thenDs` \ locals' ->
183             newSysLocalDs  (substitute tup_ty)          `thenDs` \ tup_id ->
184             mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
185                  prags                          `thenDs` \ mb_specs ->
186             let
187                 (spec_binds, rules) = unzip (catMaybes mb_specs)
188                 global' = addIdSpecialisations global rules
189                 rhs = mkLams tyvars $ mkLams dicts $
190                       mkTupleSelector locals' (locals' !! n) tup_id $
191                       mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
192             in
193             returnDs ((global', rhs) : spec_binds)
194           where
195             mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
196                                 | otherwise               = voidTy
197             ty_args    = map mk_ty_arg all_tyvars
198             substitute = substTyWith all_tyvars ty_args
199     in
200     mappM mk_bind (exports `zip` [0..])         `thenDs` \ export_binds_s ->
201      -- don't scc (auto-)annotate the tuple itself.
202
203     returnDs ((poly_tup_id, poly_tup_expr) : (concat export_binds_s ++ rest))
204
205 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
206        -> Id -> Id              -- Global, local
207        -> CoreBind -> Prag
208        -> DsM (Maybe ((Id,CoreExpr),    -- Binding for specialised Id
209                       CoreRule))        -- Rule for the Global Id
210
211 -- Example:
212 --      f :: (Eq a, Ix b) => a -> b -> b
213 --      {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
214 --
215 --      AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
216 -- 
217 --      SpecPrag (/\b.\(d:Ix b). f Int b dInt d) 
218 --               (forall b. Ix b => Int -> b -> b)
219 --
220 -- Rule:        forall b,(d:Ix b). f Int b dInt d = f_spec b d
221 --
222 -- Spec bind:   f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono 
223 --                       /\b.\(d:Ix b). in f Int b dInt d
224 --              The idea is that f occurs just once, so it'll be 
225 --              inlined and specialised
226
227 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
228   = return Nothing
229
230 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
231        (SpecPrag spec_expr spec_ty const_dicts inl)
232   = do  { let poly_name = idName poly_id
233         ; spec_name <- newLocalName poly_name
234         ; ds_spec_expr  <- dsExpr spec_expr
235         ; let (bndrs, body) = collectBinders ds_spec_expr
236               mb_lhs        = decomposeRuleLhs (bndrs ++ const_dicts) body
237
238         ; case mb_lhs of
239             Nothing -> do { warnDs msg; return Nothing }
240
241             Just (bndrs', var, args) -> return (Just (addInlineInfo inl spec_id spec_rhs, rule))
242                 where
243                   local_poly  = setIdNotExported poly_id
244                         -- Very important to make the 'f' non-exported,
245                         -- else it won't be inlined!
246                   spec_id     = mkLocalId spec_name spec_ty
247                   spec_rhs    = Let (NonRec local_poly poly_f_body) ds_spec_expr
248                   poly_f_body = mkLams (tvs ++ dicts) $
249                                 fix_up (Let mono_bind (Var mono_id))
250
251                         -- Quantify over constant dicts on the LHS, since
252                         -- their value depends only on their type
253                         -- The ones we are interested in may even be imported
254                         -- e.g. GHC.Base.dEqInt
255
256                   rule =  mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
257                                 AlwaysActive poly_name
258                                 bndrs'  -- Includes constant dicts
259                                 args
260                                 (mkVarApps (Var spec_id) bndrs)
261         }
262   where
263         -- Bind to voidTy any of all_ptvs that aren't 
264         -- relevant for this particular function 
265     fix_up body | null void_tvs = body
266                 | otherwise     = mkTyApps (mkLams void_tvs body) 
267                                            (map (const voidTy) void_tvs)
268     void_tvs = all_tvs \\ tvs
269
270     msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
271              2 (ppr spec_expr)
272 \end{code}
273
274
275 %************************************************************************
276 %*                                                                      *
277 \subsection{Adding inline pragmas}
278 %*                                                                      *
279 %************************************************************************
280
281 \begin{code}
282 decomposeRuleLhs :: [Var] -> CoreExpr -> Maybe ([Var], Id, [CoreExpr])
283 -- Returns Nothing if the LHS isn't of the expected shape
284 -- The argument 'all_bndrs' includes the "constant dicts" of the LHS,
285 -- and they may be GlobalIds, which we can't forall-ify. 
286 -- So we substitute them out instead
287 decomposeRuleLhs all_bndrs lhs 
288   = go init_env (occurAnalyseExpr lhs)  -- Occurrence analysis sorts out the dict
289                                         -- bindings so we know if they are recursive
290   where
291
292         -- all_bndrs may include top-level imported dicts, 
293         -- imported things with a for-all.  
294         -- So we localise them and subtitute them out
295     bndr_prs =  [ (id, Var (localise id)) | id <- all_bndrs, isGlobalId id ]
296     localise d = mkLocalId (idName d) (idType d)
297
298     init_env = mkVarEnv bndr_prs
299     all_bndrs' = map subst_bndr all_bndrs
300     subst_bndr bndr = case lookupVarEnv init_env bndr of
301                         Just (Var bndr') -> bndr'
302                         Just other       -> panic "decomposeRuleLhs"
303                         Nothing          -> bndr
304
305         -- Substitute dicts in the LHS args, so that there 
306         -- aren't any lets getting in the way
307         -- Note that we substitute the function too; we might have this as
308         -- a LHS:       let f71 = M.f Int in f71
309     go env (Let (NonRec dict rhs) body) 
310         = go (extendVarEnv env dict (simpleSubst env rhs)) body
311     go env body 
312         = case collectArgs (simpleSubst env body) of
313             (Var fn, args) -> Just (all_bndrs', fn, args)
314             other          -> Nothing
315
316 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
317 -- Similar to CoreSubst.substExpr, except that 
318 -- (a) takes no account of capture; dictionary bindings use new names
319 -- (b) can have a GlobalId (imported) in its domain
320 -- (c) Ids only; no types are substituted
321
322 simpleSubst subst expr
323   = go expr
324   where
325     go (Var v)         = lookupVarEnv subst v `orElse` Var v
326     go (Type ty)       = Type ty
327     go (Lit lit)       = Lit lit
328     go (App fun arg)   = App (go fun) (go arg)
329     go (Note note e)   = Note note (go e)
330     go (Lam bndr body) = Lam bndr (go body)
331     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
332     go (Let (Rec pairs) body)       = Let (Rec (mapSnd go pairs)) (go body)
333     go (Case scrut bndr ty alts)    = Case (go scrut) bndr ty 
334                                            [(c,bs,go r) | (c,bs,r) <- alts]
335
336 addInlinePrags :: [Prag] -> Id -> CoreExpr -> (Id,CoreExpr)
337 addInlinePrags prags bndr rhs
338   = case [inl | InlinePrag inl <- prags] of
339         []      -> (bndr, rhs)
340         (inl:_) -> addInlineInfo inl bndr rhs
341
342 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
343 addInlineInfo (Inline phase is_inline) bndr rhs
344   = (attach_phase bndr phase, wrap_inline is_inline rhs)
345   where
346     attach_phase bndr phase 
347         | isAlwaysActive phase = bndr   -- Default phase
348         | otherwise            = bndr `setInlinePragma` phase
349
350     wrap_inline True  body = mkInlineMe body
351     wrap_inline False body = body
352 \end{code}
353
354
355 %************************************************************************
356 %*                                                                      *
357 \subsection[addAutoScc]{Adding automatic sccs}
358 %*                                                                      *
359 %************************************************************************
360
361 \begin{code}
362 data AutoScc
363         = TopLevel
364         | TopLevelAddSccs (Id -> Maybe Id)
365         | NoSccs
366
367 addSccs :: AutoScc -> [(a,Id,Id,[Prag])] -> AutoScc
368 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
369 addSccs NoSccs   exports = NoSccs
370 addSccs TopLevel exports 
371   = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc,_) <- exports, loc == id ] of
372                                 (exp:_)  | opt_AutoSccsOnAllToplevs || 
373                                             (isExportedId exp && 
374                                              opt_AutoSccsOnExportedToplevs)
375                                         -> Just exp
376                                 _ -> Nothing)
377
378 addAutoScc :: AutoScc           -- if needs be, decorate toplevs?
379            -> (Id, CoreExpr)
380            -> DsM (Id, CoreExpr)
381
382 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr) 
383  | do_auto_scc
384      = getModuleDs `thenDs` \ mod ->
385        returnDs (bndr, mkSCC (mkAutoCC top_bndr mod NotCafCC) core_expr)
386  where do_auto_scc = isJust maybe_auto_scc
387        maybe_auto_scc = auto_scc_fn bndr
388        (Just top_bndr) = maybe_auto_scc
389
390 addAutoScc _ pair
391      = returnDs pair
392 \end{code}
393
394 If profiling and dealing with a dict binding,
395 wrap the dict in @_scc_ DICT <dict>@:
396
397 \begin{code}
398 addDictScc var rhs = returnDs rhs
399
400 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
401   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
402     || not (isDictId var)
403   = returnDs rhs                                -- That's easy: do nothing
404
405   | otherwise
406   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
407         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
408     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
409 -}
410 \end{code}
411
412
413 %************************************************************************
414 %*                                                                      *
415                 Desugaring coercions
416 %*                                                                      *
417 %************************************************************************
418
419
420 \begin{code}
421 dsCoercion :: ExprCoFn -> DsM CoreExpr -> DsM CoreExpr
422 dsCoercion CoHole            thing_inside = thing_inside
423 dsCoercion (CoCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
424 dsCoercion (CoLams ids c)    thing_inside = do { expr <- dsCoercion c thing_inside
425                                                ; return (mkLams ids expr) }
426 dsCoercion (CoTyLams tvs c)  thing_inside = do { expr <- dsCoercion c thing_inside
427                                                ; return (mkLams tvs expr) }
428 dsCoercion (CoApps c ids)    thing_inside = do { expr <- dsCoercion c thing_inside
429                                                ; return (mkVarApps expr ids) }
430 dsCoercion (CoTyApps c tys)  thing_inside = do { expr <- dsCoercion c thing_inside
431                                                ; return (mkTyApps expr tys) }
432 dsCoercion (CoLet bs c)      thing_inside = do { prs <- dsLHsBinds bs
433                                                ; expr <- dsCoercion c thing_inside
434                                                ; return (Let (Rec prs) expr) }
435 \end{code}
436
437