8ed971909fdeb1c61c37e9f867faebaccb226bc4
[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 })
93   = matchWrapper (FunRhs (idName fun)) matches          `thenDs` \ (args, body) ->
94     dsCoercion co_fn (return (mkLams args body))        `thenDs` \ rhs ->
95     returnDs ((fun,rhs) : rest)
96
97 dsHsBind auto_scc rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty })
98   = dsGuarded grhss ty                          `thenDs` \ body_expr ->
99     mkSelectorBinds pat body_expr               `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 would 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 NoSccs binds
127         ; let env = mkABEnv exports
128               do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
129                                    = addInlinePrags prags gbl_id $
130                                      addAutoScc auto_scc 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 NoSccs 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         bind    = addInlinePrags prags global' $ addAutoScc auto_scc global' rhs'
155     in
156     returnDs (bind  : spec_binds ++ rest)
157
158 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
159   = do  { core_prs <- ds_lhs_binds NoSccs binds
160         ; let env = mkABEnv exports
161               do_one (lcl_id,rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
162                                   = addInlinePrags prags lcl_id $
163                                     addAutoScc auto_scc gbl_id rhs
164                                   | otherwise = (lcl_id,rhs)
165                
166                 -- Rec because of mixed-up dictionary bindings
167               core_bind = Rec (map do_one core_prs)
168
169               tup_expr      = mkTupleExpr locals
170               tup_ty        = exprType tup_expr
171               poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
172                               Let core_bind tup_expr
173               locals        = [local | (_, _, local, _) <- exports]
174               local_tys     = map idType locals
175
176         ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
177
178         ; let dict_args = map Var dicts
179
180               mk_bind ((tyvars, global, local, prags), n)       -- locals !! n == local
181                 =       -- Need to make fresh locals to bind in the selector, because
182                         -- some of the tyvars will be bound to 'Any'
183                   do { locals' <- newSysLocalsDs (map substitute local_tys)
184                      ; tup_id  <- newSysLocalDs  (substitute tup_ty)
185                      ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
186                                          prags
187                      ; let (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                      ; returnDs ((global', rhs) : spec_binds) }
193                 where
194                   mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
195                                       | otherwise               = mkArbitraryType all_tyvar
196                   ty_args    = map mk_ty_arg all_tyvars
197                   substitute = substTyWith all_tyvars ty_args
198
199         ; export_binds_s <- mappM mk_bind (exports `zip` [0..])
200              -- don't scc (auto-)annotate the tuple itself.
201
202         ; returnDs ((poly_tup_id, poly_tup_expr) : 
203                     (concat export_binds_s ++ rest)) }
204
205 mkABEnv :: [([TyVar], Id, Id, [Prag])] -> VarEnv (Id, [Prag])
206 -- Takes the exports of a AbsBinds, and returns a mapping
207 --      lcl_id -> (gbl_id, prags)
208 mkABEnv exports = mkVarEnv [ (lcl_id, (gbl_id, prags)) 
209                            | (_, gbl_id, lcl_id, prags) <- exports]
210
211
212 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
213        -> Id -> Id              -- Global, local
214        -> CoreBind -> Prag
215        -> DsM (Maybe ((Id,CoreExpr),    -- Binding for specialised Id
216                       CoreRule))        -- Rule for the Global Id
217
218 -- Example:
219 --      f :: (Eq a, Ix b) => a -> b -> b
220 --      {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
221 --
222 --      AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
223 -- 
224 --      SpecPrag (/\b.\(d:Ix b). f Int b dInt d) 
225 --               (forall b. Ix b => Int -> b -> b)
226 --
227 -- Rule:        forall b,(d:Ix b). f Int b dInt d = f_spec b d
228 --
229 -- Spec bind:   f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono 
230 --                       /\b.\(d:Ix b). in f Int b dInt d
231 --              The idea is that f occurs just once, so it'll be 
232 --              inlined and specialised
233
234 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
235   = return Nothing
236
237 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
238        (SpecPrag spec_expr spec_ty const_dicts inl)
239   = do  { let poly_name = idName poly_id
240         ; spec_name <- newLocalName poly_name
241         ; ds_spec_expr  <- dsExpr spec_expr
242         ; let (bndrs, body) = collectBinders ds_spec_expr
243               mb_lhs        = decomposeRuleLhs (bndrs ++ const_dicts) body
244
245         ; case mb_lhs of
246             Nothing -> do { warnDs msg; return Nothing }
247
248             Just (bndrs', var, args) -> return (Just (addInlineInfo inl spec_id spec_rhs, rule))
249                 where
250                   local_poly  = setIdNotExported poly_id
251                         -- Very important to make the 'f' non-exported,
252                         -- else it won't be inlined!
253                   spec_id     = mkLocalId spec_name spec_ty
254                   spec_rhs    = Let (NonRec local_poly poly_f_body) ds_spec_expr
255                   poly_f_body = mkLams (tvs ++ dicts) $
256                                 fix_up (Let mono_bind (Var mono_id))
257
258                         -- Quantify over constant dicts on the LHS, since
259                         -- their value depends only on their type
260                         -- The ones we are interested in may even be imported
261                         -- e.g. GHC.Base.dEqInt
262
263                   rule =  mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
264                                 AlwaysActive poly_name
265                                 bndrs'  -- Includes constant dicts
266                                 args
267                                 (mkVarApps (Var spec_id) bndrs)
268         }
269   where
270         -- Bind to Any any of all_ptvs that aren't 
271         -- relevant for this particular function 
272     fix_up body | null void_tvs = body
273                 | otherwise     = mkTyApps (mkLams void_tvs body) 
274                                            (map mkArbitraryType void_tvs)
275     void_tvs = all_tvs \\ tvs
276
277     msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
278              2 (ppr spec_expr)
279 \end{code}
280
281
282 %************************************************************************
283 %*                                                                      *
284 \subsection{Adding inline pragmas}
285 %*                                                                      *
286 %************************************************************************
287
288 \begin{code}
289 decomposeRuleLhs :: [Var] -> CoreExpr -> Maybe ([Var], Id, [CoreExpr])
290 -- Returns Nothing if the LHS isn't of the expected shape
291 -- The argument 'all_bndrs' includes the "constant dicts" of the LHS,
292 -- and they may be GlobalIds, which we can't forall-ify. 
293 -- So we substitute them out instead
294 decomposeRuleLhs all_bndrs lhs 
295   = go init_env (occurAnalyseExpr lhs)  -- Occurrence analysis sorts out the dict
296                                         -- bindings so we know if they are recursive
297   where
298
299         -- all_bndrs may include top-level imported dicts, 
300         -- imported things with a for-all.  
301         -- So we localise them and subtitute them out
302     bndr_prs =  [ (id, Var (localise id)) | id <- all_bndrs, isGlobalId id ]
303     localise d = mkLocalId (idName d) (idType d)
304
305     init_env = mkVarEnv bndr_prs
306     all_bndrs' = map subst_bndr all_bndrs
307     subst_bndr bndr = case lookupVarEnv init_env bndr of
308                         Just (Var bndr') -> bndr'
309                         Just other       -> panic "decomposeRuleLhs"
310                         Nothing          -> bndr
311
312         -- Substitute dicts in the LHS args, so that there 
313         -- aren't any lets getting in the way
314         -- Note that we substitute the function too; we might have this as
315         -- a LHS:       let f71 = M.f Int in f71
316     go env (Let (NonRec dict rhs) body) 
317         = go (extendVarEnv env dict (simpleSubst env rhs)) body
318     go env body 
319         = case collectArgs (simpleSubst env body) of
320             (Var fn, args) -> Just (all_bndrs', fn, args)
321             other          -> Nothing
322
323 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
324 -- Similar to CoreSubst.substExpr, except that 
325 -- (a) takes no account of capture; dictionary bindings use new names
326 -- (b) can have a GlobalId (imported) in its domain
327 -- (c) Ids only; no types are substituted
328
329 simpleSubst subst expr
330   = go expr
331   where
332     go (Var v)         = lookupVarEnv subst v `orElse` Var v
333     go (Cast e co)     = Cast (go e) co
334     go (Type ty)       = Type ty
335     go (Lit lit)       = Lit lit
336     go (App fun arg)   = App (go fun) (go arg)
337     go (Note note e)   = Note note (go e)
338     go (Lam bndr body) = Lam bndr (go body)
339     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
340     go (Let (Rec pairs) body)       = Let (Rec (mapSnd go pairs)) (go body)
341     go (Case scrut bndr ty alts)    = Case (go scrut) bndr ty 
342                                            [(c,bs,go r) | (c,bs,r) <- alts]
343
344 addInlinePrags :: [Prag] -> Id -> CoreExpr -> (Id,CoreExpr)
345 addInlinePrags prags bndr rhs
346   = case [inl | InlinePrag inl <- prags] of
347         []      -> (bndr, rhs)
348         (inl:_) -> addInlineInfo inl bndr rhs
349
350 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
351 addInlineInfo (Inline phase is_inline) bndr rhs
352   = (attach_phase bndr phase, wrap_inline is_inline rhs)
353   where
354     attach_phase bndr phase 
355         | isAlwaysActive phase = bndr   -- Default phase
356         | otherwise            = bndr `setInlinePragma` phase
357
358     wrap_inline True  body = mkInlineMe body
359     wrap_inline False body = body
360 \end{code}
361
362
363 %************************************************************************
364 %*                                                                      *
365 \subsection[addAutoScc]{Adding automatic sccs}
366 %*                                                                      *
367 %************************************************************************
368
369 \begin{code}
370 data AutoScc = NoSccs 
371              | AddSccs Module (Id -> Bool)
372 -- The (Id->Bool) says which Ids to add SCCs to 
373
374 addAutoScc :: AutoScc   
375            -> Id        -- Binder
376            -> CoreExpr  -- Rhs
377            -> CoreExpr  -- Scc'd Rhs
378
379 addAutoScc NoSccs _ rhs
380   = rhs
381 addAutoScc (AddSccs mod add_scc) id rhs
382   | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
383   | otherwise  = rhs
384 \end{code}
385
386 If profiling and dealing with a dict binding,
387 wrap the dict in @_scc_ DICT <dict>@:
388
389 \begin{code}
390 addDictScc var rhs = returnDs rhs
391
392 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
393   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
394     || not (isDictId var)
395   = returnDs rhs                                -- That's easy: do nothing
396
397   | otherwise
398   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
399         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
400     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
401 -}
402 \end{code}
403
404
405 %************************************************************************
406 %*                                                                      *
407                 Desugaring coercions
408 %*                                                                      *
409 %************************************************************************
410
411
412 \begin{code}
413 dsCoercion :: HsWrapper -> DsM CoreExpr -> DsM CoreExpr
414 dsCoercion WpHole            thing_inside = thing_inside
415 dsCoercion (WpCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
416 dsCoercion (WpCo co)     thing_inside = do { expr <- thing_inside
417                                                ; return (Cast expr co) }
418 dsCoercion (WpLam id)        thing_inside = do { expr <- thing_inside
419                                                ; return (Lam id expr) }
420 dsCoercion (WpTyLam tv)      thing_inside = do { expr <- thing_inside
421                                                ; return (Lam tv expr) }
422 dsCoercion (WpApp id)        thing_inside = do { expr <- thing_inside
423                                                ; return (App expr (Var id)) }
424 dsCoercion (WpTyApp ty)      thing_inside = do { expr <- thing_inside
425                                                ; return (App expr (Type ty)) }
426 dsCoercion (WpLet bs)        thing_inside = do { prs <- dsLHsBinds bs
427                                                ; expr <- thing_inside
428                                                ; return (Let (Rec prs) expr) }
429 \end{code}