f03877360eda53a48e1cbce0dc3ce416a30c0fc9
[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 {-# OPTIONS -w #-}
14 -- The above warning supression flag is a temporary kludge.
15 -- While working on this module you are encouraged to remove it and fix
16 -- any warnings in the module. See
17 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
18 -- for details
19
20 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, 
21                  dsCoercion,
22                  AutoScc(..)
23   ) where
24
25 #include "HsVersions.h"
26
27 import {-# SOURCE #-}   DsExpr( dsLExpr, dsExpr )
28 import {-# SOURCE #-}   Match( matchWrapper )
29
30 import DsMonad
31 import DsGRHSs
32 import DsUtils
33
34 import HsSyn            -- lots of things
35 import CoreSyn          -- lots of things
36 import CoreUtils
37
38 import TcHsSyn          ( mkArbitraryType )     -- Mis-placed?
39 import TcType
40 import OccurAnal
41 import CostCentre
42 import Module
43 import Id
44 import Var      ( TyVar )
45 import Rules
46 import VarEnv
47 import Type
48 import Outputable
49 import SrcLoc
50 import Maybes
51 import Bag
52 import BasicTypes hiding ( TopLevel )
53 import FastString
54 import Util             ( mapSnd )
55
56 import Control.Monad
57 import Data.List
58 \end{code}
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
67 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
68 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
69
70 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
71 dsLHsBinds binds = ds_lhs_binds NoSccs binds
72
73
74 ------------------------
75 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
76          -- scc annotation policy (see below)
77 ds_lhs_binds auto_scc binds =  foldM (dsLHsBind auto_scc) [] (bagToList binds)
78
79 dsLHsBind :: AutoScc
80          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
81          -> LHsBind Id
82          -> DsM [(Id,CoreExpr)] -- Result
83 dsLHsBind auto_scc rest (L loc bind)
84   = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
85
86 dsHsBind :: AutoScc
87          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
88          -> HsBind Id
89          -> DsM [(Id,CoreExpr)] -- Result
90
91 dsHsBind auto_scc rest (VarBind var expr)
92   = dsLExpr expr                `thenDs` \ core_expr ->
93
94         -- Dictionary bindings are always VarMonoBinds, so
95         -- we only need do this here
96     addDictScc var core_expr    `thenDs` \ core_expr' ->
97     returnDs ((var, core_expr') : rest)
98
99 dsHsBind auto_scc rest (FunBind { fun_id = L _ fun, fun_matches = matches, 
100                                   fun_co_fn = co_fn, fun_tick = tick, fun_infix = inf })
101   = matchWrapper (FunRhs (idName fun) inf) matches      `thenDs` \ (args, body) ->
102     mkOptTickBox tick body                              `thenDs` \ body' ->
103     dsCoercion co_fn (return (mkLams args body'))       `thenDs` \ rhs ->
104     returnDs ((fun,rhs) : rest)
105
106 dsHsBind auto_scc rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty })
107   = dsGuarded grhss ty                          `thenDs` \ body_expr ->
108     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
109     returnDs (sel_binds ++ rest)
110
111 -- Note [Rules and inlining]
112 -- Common special case: no type or dictionary abstraction
113 -- This is a bit less trivial than you might suppose
114 -- The naive way woudl be to desguar to something like
115 --      f_lcl = ...f_lcl...     -- The "binds" from AbsBinds
116 --      M.f = f_lcl             -- Generated from "exports"
117 -- But we don't want that, because if M.f isn't exported,
118 -- it'll be inlined unconditionally at every call site (its rhs is 
119 -- trivial).  That would be ok unless it has RULES, which would 
120 -- thereby be completely lost.  Bad, bad, bad.
121 --
122 -- Instead we want to generate
123 --      M.f = ...f_lcl...
124 --      f_lcl = M.f
125 -- Now all is cool. The RULES are attached to M.f (by SimplCore), 
126 -- and f_lcl is rapidly inlined away.
127 --
128 -- This does not happen in the same way to polymorphic binds,
129 -- because they desugar to
130 --      M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
131 -- Although I'm a bit worried about whether full laziness might
132 -- float the f_lcl binding out and then inline M.f at its call site
133
134 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
135   = do  { core_prs <- ds_lhs_binds NoSccs binds
136         ; let env = mkABEnv exports
137               do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
138                                    = addInlinePrags prags gbl_id $
139                                      addAutoScc auto_scc gbl_id rhs
140                                    | otherwise = (lcl_id, rhs)
141               locals'  = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
142         ; return (map do_one core_prs ++ locals' ++ rest) }
143                 -- No Rec needed here (contrast the other AbsBinds cases)
144                 -- because we can rely on the enclosing dsBind to wrap in Rec
145
146         -- Another common case: one exported variable
147         -- Non-recursive bindings come through this way
148 dsHsBind auto_scc rest
149      (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
150   = ASSERT( all (`elem` tyvars) all_tyvars )
151     ds_lhs_binds NoSccs binds   `thenDs` \ core_prs ->
152     let 
153         -- Always treat the binds as recursive, because the typechecker
154         -- makes rather mixed-up dictionary bindings
155         core_bind = Rec core_prs
156     in
157     mappM (dsSpec all_tyvars dicts tyvars global local core_bind) 
158           prags                         `thenDs` \ mb_specs ->
159     let
160         (spec_binds, rules) = unzip (catMaybes mb_specs)
161         global' = addIdSpecialisations global rules
162         rhs'    = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
163         bind    = addInlinePrags prags global' $ addAutoScc auto_scc global' rhs'
164     in
165     returnDs (bind  : spec_binds ++ rest)
166
167 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
168   = do  { core_prs <- ds_lhs_binds NoSccs binds
169         ; let env = mkABEnv exports
170               do_one (lcl_id,rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
171                                   = addInlinePrags prags lcl_id $
172                                     addAutoScc auto_scc gbl_id rhs
173                                   | otherwise = (lcl_id,rhs)
174                
175                 -- Rec because of mixed-up dictionary bindings
176               core_bind = Rec (map do_one core_prs)
177
178               tup_expr      = mkTupleExpr locals
179               tup_ty        = exprType tup_expr
180               poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
181                               Let core_bind tup_expr
182               locals        = [local | (_, _, local, _) <- exports]
183               local_tys     = map idType locals
184
185         ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
186
187         ; let dict_args = map Var dicts
188
189               mk_bind ((tyvars, global, local, prags), n)       -- locals !! n == local
190                 =       -- Need to make fresh locals to bind in the selector, because
191                         -- some of the tyvars will be bound to 'Any'
192                   do { ty_args <- mapM mk_ty_arg all_tyvars
193                      ; let substitute = substTyWith all_tyvars ty_args
194                      ; locals' <- newSysLocalsDs (map substitute local_tys)
195                      ; tup_id  <- newSysLocalDs  (substitute tup_ty)
196                      ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
197                                          prags
198                      ; let (spec_binds, rules) = unzip (catMaybes mb_specs)
199                            global' = addIdSpecialisations global rules
200                            rhs = mkLams tyvars $ mkLams dicts $
201                                  mkTupleSelector locals' (locals' !! n) tup_id $
202                                  mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
203                      ; returnDs ((global', rhs) : spec_binds) }
204                 where
205                   mk_ty_arg all_tyvar
206                         | all_tyvar `elem` tyvars = return (mkTyVarTy all_tyvar)
207                         | otherwise               = dsMkArbitraryType all_tyvar
208
209         ; export_binds_s <- mappM mk_bind (exports `zip` [0..])
210              -- don't scc (auto-)annotate the tuple itself.
211
212         ; returnDs ((poly_tup_id, poly_tup_expr) : 
213                     (concat export_binds_s ++ rest)) }
214
215 mkABEnv :: [([TyVar], Id, Id, [LPrag])] -> VarEnv (Id, [LPrag])
216 -- Takes the exports of a AbsBinds, and returns a mapping
217 --      lcl_id -> (gbl_id, prags)
218 mkABEnv exports = mkVarEnv [ (lcl_id, (gbl_id, prags)) 
219                            | (_, gbl_id, lcl_id, prags) <- exports]
220
221
222 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
223        -> Id -> Id              -- Global, local
224        -> CoreBind -> LPrag
225        -> DsM (Maybe ((Id,CoreExpr),    -- Binding for specialised Id
226                       CoreRule))        -- Rule for the Global Id
227
228 -- Example:
229 --      f :: (Eq a, Ix b) => a -> b -> b
230 --      {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
231 --
232 --      AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
233 -- 
234 --      SpecPrag (/\b.\(d:Ix b). f Int b dInt d) 
235 --               (forall b. Ix b => Int -> b -> b)
236 --
237 -- Rule:        forall b,(d:Ix b). f Int b dInt d = f_spec b d
238 --
239 -- Spec bind:   f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono 
240 --                       /\b.\(d:Ix b). in f Int b dInt d
241 --              The idea is that f occurs just once, so it'll be 
242 --              inlined and specialised
243 --
244 -- Given SpecPrag (/\as.\ds. f es) t, we have
245 -- the defn             f_spec as ds = f es 
246 -- and the RULE         f es = f_spec as ds
247 --
248 -- It is *possible* that 'es' does not mention all of the dictionaries 'ds'
249 -- (a bit silly, because then the 
250 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (L _ (InlinePrag {}))
251   = return Nothing
252
253 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
254        (L loc (SpecPrag spec_expr spec_ty _const_dicts inl))
255         -- See Note [Const rule dicts]
256   = putSrcSpanDs loc $ 
257     do  { let poly_name = idName poly_id
258         ; spec_name <- newLocalName poly_name
259         ; ds_spec_expr  <- dsExpr spec_expr
260         ; let (bndrs, body) = collectBinders (occurAnalyseExpr ds_spec_expr)
261                 -- The occurrence-analysis does two things
262                 -- (a) identifies unused binders: Note [Unused spec binders]
263                 -- (b) sorts dict bindings into NonRecs 
264                 --      so they can be inlined by decomposeRuleLhs
265               mb_lhs = decomposeRuleLhs body
266
267         -- Check for dead binders: Note [Unused spec binders]
268         ; case filter isDeadBinder bndrs of {
269                 bs | not (null bs) -> do { warnDs (dead_msg bs); return Nothing }
270                    | otherwise -> 
271
272           case mb_lhs of
273             Nothing -> do { warnDs decomp_msg; return Nothing }
274
275             Just (var, args) -> do
276         
277         { f_body <- fix_up (Let mono_bind (Var mono_id))
278
279         ; let     local_poly  = setIdNotExported poly_id
280                         -- Very important to make the 'f' non-exported,
281                         -- else it won't be inlined!
282                   spec_id     = mkLocalId spec_name spec_ty
283                   spec_rhs    = Let (NonRec local_poly poly_f_body) ds_spec_expr
284                   poly_f_body = mkLams (tvs ++ dicts) f_body
285                                 
286                   rule =  mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
287                                 AlwaysActive poly_name
288                                 bndrs args
289                                 (mkVarApps (Var spec_id) bndrs)
290         ; return (Just (addInlineInfo inl spec_id spec_rhs, rule))
291         } } }
292   where
293         -- Bind to Any any of all_ptvs that aren't 
294         -- relevant for this particular function 
295     fix_up body | null void_tvs = return body
296                 | otherwise     = do { void_tys <- mapM dsMkArbitraryType void_tvs
297                                      ; return (mkTyApps (mkLams void_tvs body) void_tys) }
298
299     void_tvs = all_tvs \\ tvs
300
301     dead_msg bs = vcat [ sep [ptext SLIT("Useless constraint") <> plural bs
302                                  <+> ptext SLIT("in specialied type:"),
303                              nest 2 (pprTheta (map get_pred bs))]
304                        , ptext SLIT("SPECIALISE pragma ignored")]
305     get_pred b = ASSERT( isId b ) expectJust "dsSpec" (tcSplitPredTy_maybe (idType b))
306
307     decomp_msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
308                     2 (ppr spec_expr)
309
310 dsMkArbitraryType tv = mkArbitraryType warn tv
311   where
312     warn span msg = putSrcSpanDs span (warnDs msg)
313 \end{code}
314
315 Note [Unused spec binders]
316 ~~~~~~~~~~~~~~~~~~~~~~~~~~
317 Consider
318         f :: a -> a
319         {-# SPECIALISE f :: Eq a => a -> a #-}
320 It's true that this *is* a more specialised type, but the rule
321 we get is something like this:
322         f_spec d = f
323         RULE: f = f_spec d
324 Note that the rule is bogus, becuase it mentions a 'd' that is
325 not bound on the LHS!  But it's a silly specialisation anyway, becuase
326 the constraint is unused.  We could bind 'd' to (error "unused")
327 but it seems better to reject the program because it's almost certainly
328 a mistake.  That's what the isDeadBinder call detects.
329
330 Note [Const rule dicts]
331 ~~~~~~~~~~~~~~~~~~~~~~~
332 A SpecPrag has a field for "constant dicts" in the RULE, but I think
333 it's pretty useless.  See the place where it's generated in TcBinds.
334 TcSimplify will discharge a constraint by binding it to, say, 
335 GHC.Base.$f2 :: Eq Int, withour putting anything in the LIE, so this 
336 dict won't show up in the const-dicts field.  It probably doesn't matter,
337 because the rule will end up being something like
338         f Int GHC.Base.$f2 = ...
339 rather than
340         forall d. f Int d = ...
341 The latter is more general, but in practice I think it won't make any
342 difference.
343
344
345 %************************************************************************
346 %*                                                                      *
347 \subsection{Adding inline pragmas}
348 %*                                                                      *
349 %************************************************************************
350
351 \begin{code}
352 decomposeRuleLhs :: CoreExpr -> Maybe (Id, [CoreExpr])
353 -- Returns Nothing if the LHS isn't of the expected shape
354 decomposeRuleLhs lhs 
355   = go emptyVarEnv (occurAnalyseExpr lhs)       -- Occurrence analysis sorts out the dict
356                                                 -- bindings so we know if they are recursive
357   where
358         -- Substitute dicts in the LHS args, so that there 
359         -- aren't any lets getting in the way
360         -- Note that we substitute the function too; we might have this as
361         -- a LHS:       let f71 = M.f Int in f71
362     go env (Let (NonRec dict rhs) body) 
363         = go (extendVarEnv env dict (simpleSubst env rhs)) body
364     go env body 
365         = case collectArgs (simpleSubst env body) of
366             (Var fn, args) -> Just (fn, args)
367             other          -> Nothing
368
369 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
370 -- Similar to CoreSubst.substExpr, except that 
371 -- (a) takes no account of capture; dictionary bindings use new names
372 -- (b) can have a GlobalId (imported) in its domain
373 -- (c) Ids only; no types are substituted
374 --
375 -- (b) is the reason we can't use CoreSubst... and it's no longer relevant
376 --      so really we should replace simpleSubst 
377 simpleSubst subst expr
378   = go expr
379   where
380     go (Var v)         = lookupVarEnv subst v `orElse` Var v
381     go (Cast e co)     = Cast (go e) co
382     go (Type ty)       = Type ty
383     go (Lit lit)       = Lit lit
384     go (App fun arg)   = App (go fun) (go arg)
385     go (Note note e)   = Note note (go e)
386     go (Lam bndr body) = Lam bndr (go body)
387     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
388     go (Let (Rec pairs) body)       = Let (Rec (mapSnd go pairs)) (go body)
389     go (Case scrut bndr ty alts)    = Case (go scrut) bndr ty 
390                                            [(c,bs,go r) | (c,bs,r) <- alts]
391
392 addInlinePrags :: [LPrag] -> Id -> CoreExpr -> (Id,CoreExpr)
393 addInlinePrags prags bndr rhs
394   = case [inl | L _ (InlinePrag inl) <- prags] of
395         []      -> (bndr, rhs)
396         (inl:_) -> addInlineInfo inl bndr rhs
397
398 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
399 addInlineInfo (Inline phase is_inline) bndr rhs
400   = (attach_phase bndr phase, wrap_inline is_inline rhs)
401   where
402     attach_phase bndr phase 
403         | isAlwaysActive phase = bndr   -- Default phase
404         | otherwise            = bndr `setInlinePragma` phase
405
406     wrap_inline True  body = mkInlineMe body
407     wrap_inline False body = body
408 \end{code}
409
410
411 %************************************************************************
412 %*                                                                      *
413 \subsection[addAutoScc]{Adding automatic sccs}
414 %*                                                                      *
415 %************************************************************************
416
417 \begin{code}
418 data AutoScc = NoSccs 
419              | AddSccs Module (Id -> Bool)
420 -- The (Id->Bool) says which Ids to add SCCs to 
421
422 addAutoScc :: AutoScc   
423            -> Id        -- Binder
424            -> CoreExpr  -- Rhs
425            -> CoreExpr  -- Scc'd Rhs
426
427 addAutoScc NoSccs _ rhs
428   = rhs
429 addAutoScc (AddSccs mod add_scc) id rhs
430   | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
431   | otherwise  = rhs
432 \end{code}
433
434 If profiling and dealing with a dict binding,
435 wrap the dict in @_scc_ DICT <dict>@:
436
437 \begin{code}
438 addDictScc var rhs = returnDs rhs
439
440 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
441   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
442     || not (isDictId var)
443   = returnDs rhs                                -- That's easy: do nothing
444
445   | otherwise
446   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
447         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
448     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
449 -}
450 \end{code}
451
452
453 %************************************************************************
454 %*                                                                      *
455                 Desugaring coercions
456 %*                                                                      *
457 %************************************************************************
458
459
460 \begin{code}
461 dsCoercion :: HsWrapper -> DsM CoreExpr -> DsM CoreExpr
462 dsCoercion WpHole            thing_inside = thing_inside
463 dsCoercion (WpCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
464 dsCoercion (WpCo co)     thing_inside = do { expr <- thing_inside
465                                                ; return (Cast expr co) }
466 dsCoercion (WpLam id)        thing_inside = do { expr <- thing_inside
467                                                ; return (Lam id expr) }
468 dsCoercion (WpTyLam tv)      thing_inside = do { expr <- thing_inside
469                                                ; return (Lam tv expr) }
470 dsCoercion (WpApp id)        thing_inside = do { expr <- thing_inside
471                                                ; return (App expr (Var id)) }
472 dsCoercion (WpTyApp ty)      thing_inside = do { expr <- thing_inside
473                                                ; return (App expr (Type ty)) }
474 dsCoercion WpInline          thing_inside = do { expr <- thing_inside
475                                                ; return (mkInlineMe expr) }
476 dsCoercion (WpLet bs)        thing_inside = do { prs <- dsLHsBinds bs
477                                                ; expr <- thing_inside
478                                                ; return (Let (Rec prs) expr) }
479 \end{code}