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
32 import TcHsSyn ( mkArbitraryType ) -- Mis-placed?
47 import BasicTypes hiding ( TopLevel )
49 import Util ( mapSnd )
55 %************************************************************************
57 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
59 %************************************************************************
62 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
63 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
65 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
66 dsLHsBinds binds = ds_lhs_binds NoSccs binds
69 ------------------------
70 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
71 -- scc annotation policy (see below)
72 ds_lhs_binds auto_scc binds = foldM (dsLHsBind auto_scc) [] (bagToList binds)
75 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
77 -> DsM [(Id,CoreExpr)] -- Result
78 dsLHsBind auto_scc rest (L loc bind)
79 = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
82 -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
84 -> DsM [(Id,CoreExpr)] -- Result
86 dsHsBind _ rest (VarBind var expr) = do
87 core_expr <- dsLExpr expr
89 -- Dictionary bindings are always VarMonoBinds, so
90 -- we only need do this here
91 core_expr' <- addDictScc var core_expr
92 return ((var, core_expr') : rest)
94 dsHsBind _ rest (FunBind { fun_id = L _ fun, fun_matches = matches,
95 fun_co_fn = co_fn, fun_tick = tick, fun_infix = inf }) = do
96 (args, body) <- matchWrapper (FunRhs (idName fun) inf) matches
97 body' <- mkOptTickBox tick body
98 rhs <- dsCoercion co_fn (return (mkLams args body'))
99 return ((fun,rhs) : rest)
101 dsHsBind _ rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }) = do
102 body_expr <- dsGuarded grhss ty
103 sel_binds <- mkSelectorBinds pat body_expr
104 return (sel_binds ++ rest)
106 -- Note [Rules and inlining]
107 -- Common special case: no type or dictionary abstraction
108 -- This is a bit less trivial than you might suppose
109 -- The naive way woudl be to desguar to something like
110 -- f_lcl = ...f_lcl... -- The "binds" from AbsBinds
111 -- M.f = f_lcl -- Generated from "exports"
112 -- But we don't want that, because if M.f isn't exported,
113 -- it'll be inlined unconditionally at every call site (its rhs is
114 -- trivial). That would be ok unless it has RULES, which would
115 -- thereby be completely lost. Bad, bad, bad.
117 -- Instead we want to generate
120 -- Now all is cool. The RULES are attached to M.f (by SimplCore),
121 -- and f_lcl is rapidly inlined away.
123 -- This does not happen in the same way to polymorphic binds,
124 -- because they desugar to
125 -- M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
126 -- Although I'm a bit worried about whether full laziness might
127 -- float the f_lcl binding out and then inline M.f at its call site
129 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
130 = do { core_prs <- ds_lhs_binds NoSccs binds
131 ; let env = mkABEnv exports
132 do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
133 = addInlinePrags prags gbl_id $
134 addAutoScc auto_scc gbl_id rhs
135 | otherwise = (lcl_id, rhs)
136 locals' = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
137 ; return (map do_one core_prs ++ locals' ++ rest) }
138 -- No Rec needed here (contrast the other AbsBinds cases)
139 -- because we can rely on the enclosing dsBind to wrap in Rec
141 -- Another common case: one exported variable
142 -- Non-recursive bindings come through this way
143 dsHsBind auto_scc rest
144 (AbsBinds all_tyvars dicts [(tyvars, global, local, prags)] binds)
145 = ASSERT( all (`elem` tyvars) all_tyvars ) do
146 core_prs <- ds_lhs_binds NoSccs binds
148 -- Always treat the binds as recursive, because the typechecker
149 -- makes rather mixed-up dictionary bindings
150 core_bind = Rec core_prs
152 mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind) prags
154 (spec_binds, rules) = unzip (catMaybes mb_specs)
155 global' = addIdSpecialisations global rules
156 rhs' = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
157 bind = addInlinePrags prags global' $ addAutoScc auto_scc global' rhs'
159 return (bind : spec_binds ++ rest)
161 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
162 = do { core_prs <- ds_lhs_binds NoSccs binds
163 ; let env = mkABEnv exports
164 do_one (lcl_id,rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
165 = addInlinePrags prags lcl_id $
166 addAutoScc auto_scc gbl_id rhs
167 | otherwise = (lcl_id,rhs)
169 -- Rec because of mixed-up dictionary bindings
170 core_bind = Rec (map do_one core_prs)
172 tup_expr = mkBigCoreVarTup locals
173 tup_ty = exprType tup_expr
174 poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
175 Let core_bind tup_expr
176 locals = [local | (_, _, local, _) <- exports]
177 local_tys = map idType locals
179 ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
181 ; let dict_args = map Var dicts
183 mk_bind ((tyvars, global, local, prags), n) -- locals !! n == local
184 = -- Need to make fresh locals to bind in the selector, because
185 -- some of the tyvars will be bound to 'Any'
186 do { ty_args <- mapM mk_ty_arg all_tyvars
187 ; let substitute = substTyWith all_tyvars ty_args
188 ; 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)
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 ; return ((global', rhs) : spec_binds) }
200 | all_tyvar `elem` tyvars = return (mkTyVarTy all_tyvar)
201 | otherwise = dsMkArbitraryType all_tyvar
203 ; export_binds_s <- mapM mk_bind (exports `zip` [0..])
204 -- don't scc (auto-)annotate the tuple itself.
206 ; return ((poly_tup_id, poly_tup_expr) :
207 (concat export_binds_s ++ rest)) }
209 mkABEnv :: [([TyVar], Id, Id, [LPrag])] -> VarEnv (Id, [LPrag])
210 -- Takes the exports of a AbsBinds, and returns a mapping
211 -- lcl_id -> (gbl_id, prags)
212 mkABEnv exports = mkVarEnv [ (lcl_id, (gbl_id, prags))
213 | (_, gbl_id, lcl_id, prags) <- exports]
216 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
217 -> Id -> Id -- Global, local
219 -> DsM (Maybe ((Id,CoreExpr), -- Binding for specialised Id
220 CoreRule)) -- Rule for the Global Id
223 -- f :: (Eq a, Ix b) => a -> b -> b
224 -- {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
226 -- AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
228 -- SpecPrag (/\b.\(d:Ix b). f Int b dInt d)
229 -- (forall b. Ix b => Int -> b -> b)
231 -- Rule: forall b,(d:Ix b). f Int b dInt d = f_spec b d
233 -- Spec bind: f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono
234 -- /\b.\(d:Ix b). in f Int b dInt d
235 -- The idea is that f occurs just once, so it'll be
236 -- inlined and specialised
238 -- Given SpecPrag (/\as.\ds. f es) t, we have
239 -- the defn f_spec as ds = let-nonrec f = /\fas\fds. let f_mono = <f-rhs> in f_mono
241 -- and the RULE forall as, ds. f es = f_spec as ds
243 -- It is *possible* that 'es' does not mention all of the dictionaries 'ds'
244 -- (a bit silly, because then the
245 dsSpec _ _ _ _ _ _ (L _ (InlinePrag {}))
248 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
249 (L loc (SpecPrag spec_expr spec_ty inl))
251 do { let poly_name = idName poly_id
252 ; spec_name <- newLocalName poly_name
253 ; ds_spec_expr <- dsExpr spec_expr
254 ; let (bndrs, body) = collectBinders (occurAnalyseExpr ds_spec_expr)
255 -- The occurrence-analysis does two things
256 -- (a) identifies unused binders: Note [Unused spec binders]
257 -- (b) sorts dict bindings into NonRecs
258 -- so they can be inlined by decomposeRuleLhs
259 mb_lhs = decomposeRuleLhs body
261 -- Check for dead binders: Note [Unused spec binders]
262 ; case filter isDeadBinder bndrs of {
263 bs | not (null bs) -> do { warnDs (dead_msg bs); return Nothing }
267 Nothing -> do { warnDs decomp_msg; return Nothing }
271 { f_body <- fix_up (Let mono_bind (Var mono_id))
273 ; let local_poly = setIdNotExported poly_id
274 -- Very important to make the 'f' non-exported,
275 -- else it won't be inlined!
276 spec_id = mkLocalId spec_name spec_ty
277 spec_rhs = Let (NonRec local_poly poly_f_body) ds_spec_expr
278 poly_f_body = mkLams (tvs ++ dicts) f_body
280 extra_dict_bndrs = filter isDictId (varSetElems (exprFreeVars ds_spec_expr))
281 -- Note [Const rule dicts]
283 rule = mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
284 AlwaysActive poly_name
285 (extra_dict_bndrs ++ bndrs) args
286 (mkVarApps (Var spec_id) bndrs)
287 ; return (Just (addInlineInfo inl spec_id spec_rhs, rule))
290 -- Bind to Any any of all_ptvs that aren't
291 -- relevant for this particular function
292 fix_up body | null void_tvs = return body
293 | otherwise = do { void_tys <- mapM dsMkArbitraryType void_tvs
294 ; return (mkTyApps (mkLams void_tvs body) void_tys) }
296 void_tvs = all_tvs \\ tvs
298 dead_msg bs = vcat [ sep [ptext (sLit "Useless constraint") <> plural bs
299 <+> ptext (sLit "in specialied type:"),
300 nest 2 (pprTheta (map get_pred bs))]
301 , ptext (sLit "SPECIALISE pragma ignored")]
302 get_pred b = ASSERT( isId b ) expectJust "dsSpec" (tcSplitPredTy_maybe (idType b))
304 decomp_msg = hang (ptext (sLit "Specialisation too complicated to desugar; ignored"))
307 dsMkArbitraryType :: TcTyVar -> DsM Type
308 dsMkArbitraryType tv = mkArbitraryType warn tv
310 warn span msg = putSrcSpanDs span (warnDs msg)
313 Note [Unused spec binders]
314 ~~~~~~~~~~~~~~~~~~~~~~~~~~
317 {-# SPECIALISE f :: Eq a => a -> a #-}
318 It's true that this *is* a more specialised type, but the rule
319 we get is something like this:
322 Note that the rule is bogus, becuase it mentions a 'd' that is
323 not bound on the LHS! But it's a silly specialisation anyway, becuase
324 the constraint is unused. We could bind 'd' to (error "unused")
325 but it seems better to reject the program because it's almost certainly
326 a mistake. That's what the isDeadBinder call detects.
328 Note [Const rule dicts]
329 ~~~~~~~~~~~~~~~~~~~~~~~
330 When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict,
331 which is presumably in scope at the function definition site, we can quantify
332 over it too. *Any* dict with that type will do.
334 So for example when you have
337 {-# SPECIALISE f :: Int -> Int #-}
339 Then we get the SpecPrag
340 SpecPrag (f Int dInt) Int
342 And from that we want the rule
344 RULE forall dInt. f Int dInt = f_spec
345 f_spec = let f = <rhs> in f Int dInt
349 %************************************************************************
351 \subsection{Adding inline pragmas}
353 %************************************************************************
356 decomposeRuleLhs :: CoreExpr -> Maybe (Id, [CoreExpr])
357 -- Returns Nothing if the LHS isn't of the expected shape
359 = go emptyVarEnv (occurAnalyseExpr lhs) -- Occurrence analysis sorts out the dict
360 -- bindings so we know if they are recursive
362 -- Substitute dicts in the LHS args, so that there
363 -- aren't any lets getting in the way
364 -- Note that we substitute the function too; we might have this as
365 -- a LHS: let f71 = M.f Int in f71
366 go env (Let (NonRec dict rhs) body)
367 = go (extendVarEnv env dict (simpleSubst env rhs)) body
369 = case collectArgs (simpleSubst env body) of
370 (Var fn, args) -> Just (fn, args)
373 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
374 -- Similar to CoreSubst.substExpr, except that
375 -- (a) takes no account of capture; dictionary bindings use new names
376 -- (b) can have a GlobalId (imported) in its domain
377 -- (c) Ids only; no types are substituted
379 -- (b) is the reason we can't use CoreSubst... and it's no longer relevant
380 -- so really we should replace simpleSubst
381 simpleSubst subst expr
384 go (Var v) = lookupVarEnv subst v `orElse` Var v
385 go (Cast e co) = Cast (go e) co
386 go (Type ty) = Type ty
387 go (Lit lit) = Lit lit
388 go (App fun arg) = App (go fun) (go arg)
389 go (Note note e) = Note note (go e)
390 go (Lam bndr body) = Lam bndr (go body)
391 go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
392 go (Let (Rec pairs) body) = Let (Rec (mapSnd go pairs)) (go body)
393 go (Case scrut bndr ty alts) = Case (go scrut) bndr ty
394 [(c,bs,go r) | (c,bs,r) <- alts]
396 addInlinePrags :: [LPrag] -> Id -> CoreExpr -> (Id,CoreExpr)
397 addInlinePrags prags bndr rhs
398 = case [inl | L _ (InlinePrag inl) <- prags] of
400 (inl:_) -> addInlineInfo inl bndr rhs
402 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
403 addInlineInfo (Inline phase is_inline) bndr rhs
404 = (attach_phase bndr phase, wrap_inline is_inline rhs)
406 attach_phase bndr phase
407 | isAlwaysActive phase = bndr -- Default phase
408 | otherwise = bndr `setInlinePragma` phase
410 wrap_inline True body = mkInlineMe body
411 wrap_inline False body = body
415 %************************************************************************
417 \subsection[addAutoScc]{Adding automatic sccs}
419 %************************************************************************
422 data AutoScc = NoSccs
423 | AddSccs Module (Id -> Bool)
424 -- The (Id->Bool) says which Ids to add SCCs to
426 addAutoScc :: AutoScc
429 -> CoreExpr -- Scc'd Rhs
431 addAutoScc NoSccs _ rhs
433 addAutoScc (AddSccs mod add_scc) id rhs
434 | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
438 If profiling and dealing with a dict binding,
439 wrap the dict in @_scc_ DICT <dict>@:
442 addDictScc :: Id -> CoreExpr -> DsM CoreExpr
443 addDictScc _ rhs = return rhs
445 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
446 | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
447 || not (isDictId var)
448 = return rhs -- That's easy: do nothing
451 = do (mod, grp) <- getModuleAndGroupDs
452 -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
453 return (Note (SCC (mkAllDictsCC mod grp False)) rhs)
458 %************************************************************************
462 %************************************************************************
466 dsCoercion :: HsWrapper -> DsM CoreExpr -> DsM CoreExpr
467 dsCoercion WpHole thing_inside = thing_inside
468 dsCoercion (WpCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
469 dsCoercion (WpCast co) thing_inside = do { expr <- thing_inside
470 ; return (Cast expr co) }
471 dsCoercion (WpLam id) thing_inside = do { expr <- thing_inside
472 ; return (Lam id expr) }
473 dsCoercion (WpTyLam tv) thing_inside = do { expr <- thing_inside
474 ; return (Lam tv expr) }
475 dsCoercion (WpApp id) thing_inside = do { expr <- thing_inside
476 ; return (App expr (Var id)) }
477 dsCoercion (WpTyApp ty) thing_inside = do { expr <- thing_inside
478 ; return (App expr (Type ty)) }
479 dsCoercion WpInline thing_inside = do { expr <- thing_inside
480 ; return (mkInlineMe expr) }
481 dsCoercion (WpLet bs) thing_inside = do { prs <- dsLHsBinds bs
482 ; expr <- thing_inside
483 ; return (Let (Rec prs) expr) }