2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Pattern-matching bindings (HsBinds and MonoBinds)
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).
13 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs,
18 #include "HsVersions.h"
20 import {-# SOURCE #-} DsExpr( dsLExpr, dsExpr )
21 import {-# SOURCE #-} Match( matchWrapper )
27 import HsSyn -- lots of things
28 import CoreSyn -- lots of things
31 import TcHsSyn ( mkArbitraryType ) -- Mis-placed?
37 import Var ( TyVar, Var )
45 import BasicTypes hiding ( TopLevel )
47 import Util ( mapSnd )
53 %************************************************************************
55 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
57 %************************************************************************
60 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
61 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
63 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
64 dsLHsBinds binds = ds_lhs_binds NoSccs binds
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)
73 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
75 -> DsM [(Id,CoreExpr)] -- Result
76 dsLHsBind auto_scc rest (L loc bind)
77 = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
80 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
82 -> DsM [(Id,CoreExpr)] -- Result
84 dsHsBind auto_scc rest (VarBind var expr)
85 = dsLExpr expr `thenDs` \ core_expr ->
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)
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)
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)
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.
113 -- Instead we want to generate
116 -- Now all is cool. The RULES are attached to M.f (by SimplCore),
117 -- and f_lcl is rapidly inlined away.
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
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
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 ->
144 -- Always treat the binds as recursive, because the typechecker
145 -- makes rather mixed-up dictionary bindings
146 core_bind = Rec core_prs
148 mappM (dsSpec all_tyvars dicts tyvars global local core_bind)
149 prags `thenDs` \ mb_specs ->
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'
156 returnDs (bind : spec_binds ++ rest)
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)
166 -- Rec because of mixed-up dictionary bindings
167 core_bind = Rec (map do_one core_prs)
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
176 ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
178 ; let dict_args = map Var dicts
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)
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) }
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
199 ; export_binds_s <- mappM mk_bind (exports `zip` [0..])
200 -- don't scc (auto-)annotate the tuple itself.
202 ; returnDs ((poly_tup_id, poly_tup_expr) :
203 (concat export_binds_s ++ rest)) }
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]
212 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
213 -> Id -> Id -- Global, local
215 -> DsM (Maybe ((Id,CoreExpr), -- Binding for specialised Id
216 CoreRule)) -- Rule for the Global Id
219 -- f :: (Eq a, Ix b) => a -> b -> b
220 -- {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
222 -- AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
224 -- SpecPrag (/\b.\(d:Ix b). f Int b dInt d)
225 -- (forall b. Ix b => Int -> b -> b)
227 -- Rule: forall b,(d:Ix b). f Int b dInt d = f_spec b d
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
234 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
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
246 Nothing -> do { warnDs msg; return Nothing }
248 Just (bndrs', var, args) -> return (Just (addInlineInfo inl spec_id spec_rhs, rule))
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))
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
263 rule = mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
264 AlwaysActive poly_name
265 bndrs' -- Includes constant dicts
267 (mkVarApps (Var spec_id) bndrs)
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
277 msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
282 %************************************************************************
284 \subsection{Adding inline pragmas}
286 %************************************************************************
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
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)
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"
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
319 = case collectArgs (simpleSubst env body) of
320 (Var fn, args) -> Just (all_bndrs', fn, args)
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
329 simpleSubst subst expr
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]
344 addInlinePrags :: [Prag] -> Id -> CoreExpr -> (Id,CoreExpr)
345 addInlinePrags prags bndr rhs
346 = case [inl | InlinePrag inl <- prags] of
348 (inl:_) -> addInlineInfo inl bndr rhs
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)
354 attach_phase bndr phase
355 | isAlwaysActive phase = bndr -- Default phase
356 | otherwise = bndr `setInlinePragma` phase
358 wrap_inline True body = mkInlineMe body
359 wrap_inline False body = body
363 %************************************************************************
365 \subsection[addAutoScc]{Adding automatic sccs}
367 %************************************************************************
370 data AutoScc = NoSccs
371 | AddSccs Module (Id -> Bool)
372 -- The (Id->Bool) says which Ids to add SCCs to
374 addAutoScc :: AutoScc
377 -> CoreExpr -- Scc'd Rhs
379 addAutoScc NoSccs _ rhs
381 addAutoScc (AddSccs mod add_scc) id rhs
382 | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
386 If profiling and dealing with a dict binding,
387 wrap the dict in @_scc_ DICT <dict>@:
390 addDictScc var rhs = returnDs rhs
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
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)
405 %************************************************************************
409 %************************************************************************
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) }