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