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