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