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