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