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