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