[project @ 2005-03-18 13:37:27 by simonmar]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsBinds]{Pattern-matching bindings (HsBinds and MonoBinds)}
5
6 Handles @HsBinds@; those at the top level require different handling,
7 in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
8 lower levels it is preserved with @let@/@letrec@s).
9
10 \begin{code}
11 module DsBinds ( dsHsBinds, dsHsNestedBinds, AutoScc(..) ) where
12
13 #include "HsVersions.h"
14
15
16 import {-# SOURCE #-}   DsExpr( dsLExpr )
17 import {-# SOURCE #-}   Match( matchWrapper )
18
19 import DsMonad
20 import DsGRHSs          ( dsGuarded )
21 import DsUtils
22
23 import HsSyn            -- lots of things
24 import CoreSyn          -- lots of things
25 import CoreUtils        ( exprType, mkInlineMe, mkSCC )
26
27 import StaticFlags      ( opt_AutoSccsOnAllToplevs,
28                           opt_AutoSccsOnExportedToplevs )
29 import CostCentre       ( mkAutoCC, IsCafCC(..) )
30 import Id               ( idType, idName, isExportedId, isSpecPragmaId, Id )
31 import NameSet
32 import VarSet
33 import Type             ( mkTyVarTy, substTyWith )
34 import TysWiredIn       ( voidTy )
35 import Outputable
36 import SrcLoc           ( Located(..) )
37 import Maybe            ( isJust )
38 import Bag              ( bagToList )
39 import Monad            ( foldM )
40 \end{code}
41
42 %************************************************************************
43 %*                                                                      *
44 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
45 %*                                                                      *
46 %************************************************************************
47
48 \begin{code}
49 dsHsNestedBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
50 dsHsNestedBinds binds = dsHsBinds NoSccs binds []
51
52 dsHsBinds :: AutoScc             -- scc annotation policy (see below)
53           -> LHsBinds Id
54           -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
55           -> DsM [(Id,CoreExpr)] -- Result
56
57 dsHsBinds auto_scc binds rest
58   =  foldM (dsLHsBind auto_scc) rest (bagToList binds)
59
60 dsLHsBind :: AutoScc
61          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
62          -> LHsBind Id
63          -> DsM [(Id,CoreExpr)] -- Result
64 dsLHsBind auto_scc rest (L loc bind)
65   = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
66
67 dsHsBind :: AutoScc
68          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
69          -> HsBind Id
70          -> DsM [(Id,CoreExpr)] -- Result
71
72 dsHsBind auto_scc rest (VarBind var expr)
73   = dsLExpr expr                `thenDs` \ core_expr ->
74
75         -- Dictionary bindings are always VarMonoBinds, so
76         -- we only need do this here
77     addDictScc var core_expr    `thenDs` \ core_expr' ->
78
79     let
80         -- Gross hack to prevent inlining into SpecPragmaId rhss
81         -- Consider     fromIntegral = fromInteger . toInteger
82         --              spec1 = fromIntegral Int Float
83         -- Even though fromIntegral is small we don't want to inline
84         -- it inside spec1, so that we collect the specialised call
85         -- Solution: make spec1 an INLINE thing.  
86         core_expr'' = mkInline (isSpecPragmaId var) core_expr'
87     in  
88
89     returnDs ((var, core_expr'') : rest)
90
91 dsHsBind auto_scc rest (FunBind (L _ fun) _ matches)
92   = matchWrapper (FunRhs (idName fun)) matches          `thenDs` \ (args, body) ->
93     addAutoScc auto_scc (fun, mkLams args body)         `thenDs` \ pair ->
94     returnDs (pair : rest)
95
96 dsHsBind auto_scc rest (PatBind pat grhss ty)
97   = dsGuarded grhss ty                          `thenDs` \ body_expr ->
98     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
99     mappM (addAutoScc auto_scc) sel_binds       `thenDs` \ sel_binds ->
100     returnDs (sel_binds ++ rest)
101
102         -- Common special case: no type or dictionary abstraction
103         -- For the (rare) case when there are some mixed-up
104         -- dictionary bindings (for which a Rec is convenient)
105         -- we reply on the enclosing dsBind to wrap a Rec around.
106 dsHsBind auto_scc rest (AbsBinds [] [] exports inlines binds)
107   = dsHsBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
108     let
109         core_prs' = addLocalInlines exports inlines core_prs
110         exports'  = [(global, Var local) | (_, global, local) <- exports]
111     in
112     returnDs (core_prs' ++ exports' ++ rest)
113
114         -- Another common case: one exported variable
115         -- Non-recursive bindings come through this way
116 dsHsBind auto_scc rest
117      (AbsBinds all_tyvars dicts exps@[(tyvars, global, local)] inlines binds)
118   = ASSERT( all (`elem` tyvars) all_tyvars )
119     dsHsBinds (addSccs auto_scc exps) binds []  `thenDs` \ core_prs ->
120     let 
121         -- Always treat the binds as recursive, because the typechecker
122         -- makes rather mixed-up dictionary bindings
123         core_bind = Rec core_prs
124
125         -- The mkInline does directly what the 
126         -- addLocalInlines do in the other cases
127         export'    = (global, mkInline (idName global `elemNameSet` inlines) $
128                               mkLams tyvars $ mkLams dicts $ 
129                               Let core_bind (Var local))
130     in
131     returnDs (export' : rest)
132
133 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports inlines binds)
134   = dsHsBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
135     let 
136         -- Rec because of mixed-up dictionary bindings
137         core_bind = Rec (addLocalInlines exports inlines core_prs)
138
139         tup_expr      = mkTupleExpr locals
140         tup_ty        = exprType tup_expr
141         poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
142                         Let core_bind tup_expr
143         locals        = [local | (_, _, local) <- exports]
144         local_tys     = map idType locals
145     in
146     newSysLocalDs (exprType poly_tup_expr)              `thenDs` \ poly_tup_id ->
147     let
148         dict_args = map Var dicts
149
150         mk_bind ((tyvars, global, local), n)    -- locals !! n == local
151           =     -- Need to make fresh locals to bind in the selector, because
152                 -- some of the tyvars will be bound to voidTy
153             newSysLocalsDs (map substitute local_tys)   `thenDs` \ locals' ->
154             newSysLocalDs  (substitute tup_ty)          `thenDs` \ tup_id ->
155             returnDs (global, mkLams tyvars $ mkLams dicts $
156                               mkTupleSelector locals' (locals' !! n) tup_id $
157                               mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args)
158           where
159             mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
160                                 | otherwise               = voidTy
161             ty_args    = map mk_ty_arg all_tyvars
162             substitute = substTyWith all_tyvars ty_args
163     in
164     mappM mk_bind (exports `zip` [0..])         `thenDs` \ export_binds ->
165      -- don't scc (auto-)annotate the tuple itself.
166     returnDs ((poly_tup_id, poly_tup_expr) : (export_binds ++ rest))
167 \end{code}
168
169
170 %************************************************************************
171 %*                                                                      *
172 \subsection{Adding inline pragmas}
173 %*                                                                      *
174 %************************************************************************
175
176 \begin{code}
177 mkInline :: Bool -> CoreExpr -> CoreExpr
178 mkInline True  body = mkInlineMe body
179 mkInline False body = body
180
181 addLocalInlines :: [(a, Id, Id)] -> NameSet -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
182 addLocalInlines exports inlines pairs
183   = [(bndr, mkInline (bndr `elemVarSet` local_inlines) rhs) | (bndr,rhs) <- pairs]
184   where
185     local_inlines = mkVarSet [l | (_,g,l) <- exports, idName g `elemNameSet` inlines]
186 \end{code}
187
188
189 %************************************************************************
190 %*                                                                      *
191 \subsection[addAutoScc]{Adding automatic sccs}
192 %*                                                                      *
193 %************************************************************************
194
195 \begin{code}
196 data AutoScc
197         = TopLevel
198         | TopLevelAddSccs (Id -> Maybe Id)
199         | NoSccs
200
201 addSccs :: AutoScc -> [(a,Id,Id)] -> AutoScc
202 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
203 addSccs NoSccs   exports = NoSccs
204 addSccs TopLevel exports 
205   = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc) <- exports, loc == id ] of
206                                 (exp:_)  | opt_AutoSccsOnAllToplevs || 
207                                             (isExportedId exp && 
208                                              opt_AutoSccsOnExportedToplevs)
209                                         -> Just exp
210                                 _ -> Nothing)
211
212 addAutoScc :: AutoScc           -- if needs be, decorate toplevs?
213            -> (Id, CoreExpr)
214            -> DsM (Id, CoreExpr)
215
216 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr) 
217  | do_auto_scc
218      = getModuleDs `thenDs` \ mod ->
219        returnDs (bndr, mkSCC (mkAutoCC top_bndr mod NotCafCC) core_expr)
220  where do_auto_scc = isJust maybe_auto_scc
221        maybe_auto_scc = auto_scc_fn bndr
222        (Just top_bndr) = maybe_auto_scc
223
224 addAutoScc _ pair
225      = returnDs pair
226 \end{code}
227
228 If profiling and dealing with a dict binding,
229 wrap the dict in @_scc_ DICT <dict>@:
230
231 \begin{code}
232 addDictScc var rhs = returnDs rhs
233
234 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
235   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
236     || not (isDictTy (idType var))
237   = returnDs rhs                                -- That's easy: do nothing
238
239   | otherwise
240   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
241         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
242     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
243 -}
244 \end{code}