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