Implement INLINABLE pragma
[ghc-hetmet.git] / compiler / vectorise / Vectorise / Exp.hs
1
2 -- | Vectorisation of expressions.
3 module Vectorise.Exp
4         (vectPolyExpr)
5 where
6 import Vectorise.Utils
7 import Vectorise.Type.Type
8 import Vectorise.Var
9 import Vectorise.Vect
10 import Vectorise.Env
11 import Vectorise.Monad
12 import Vectorise.Builtins
13
14 import CoreSyn
15 import CoreUtils
16 import MkCore
17 import CoreFVs
18 import DataCon
19 import TyCon
20 import Type
21 import Var
22 import VarEnv
23 import VarSet
24 import Id
25 import BasicTypes( isLoopBreaker )
26 import Literal
27 import TysWiredIn
28 import TysPrim
29 import Outputable
30 import FastString
31 import Control.Monad
32 import Data.List
33
34
35 -- | Vectorise a polymorphic expression.
36 vectPolyExpr 
37         :: Bool                 -- ^ When vectorising the RHS of a binding, whether that
38                                 --   binding is a loop breaker.
39         -> CoreExprWithFVs
40         -> VM (Inline, VExpr)
41
42 vectPolyExpr loop_breaker (_, AnnNote note expr)
43  = do (inline, expr') <- vectPolyExpr loop_breaker expr
44       return (inline, vNote note expr')
45
46 vectPolyExpr loop_breaker expr
47  = do
48       arity <- polyArity tvs
49       polyAbstract tvs $ \args ->
50         do
51           (inline, mono') <- vectFnExpr False loop_breaker mono
52           return (addInlineArity inline arity,
53                   mapVect (mkLams $ tvs ++ args) mono')
54   where
55     (tvs, mono) = collectAnnTypeBinders expr
56
57
58 -- | Vectorise an expression.
59 vectExpr :: CoreExprWithFVs -> VM VExpr
60 vectExpr (_, AnnType ty)
61   = liftM vType (vectType ty)
62
63 vectExpr (_, AnnVar v) 
64   = vectVar v
65
66 vectExpr (_, AnnLit lit) 
67   = vectLiteral lit
68
69 vectExpr (_, AnnNote note expr)
70   = liftM (vNote note) (vectExpr expr)
71
72 vectExpr e@(_, AnnApp _ arg)
73   | isAnnTypeArg arg
74   = vectTyAppExpr fn tys
75   where
76     (fn, tys) = collectAnnTypeArgs e
77
78 vectExpr (_, AnnApp (_, AnnVar v) (_, AnnLit lit))
79   | Just con <- isDataConId_maybe v
80   , is_special_con con
81   = do
82       let vexpr = App (Var v) (Lit lit)
83       lexpr <- liftPD vexpr
84       return (vexpr, lexpr)
85   where
86     is_special_con con = con `elem` [intDataCon, floatDataCon, doubleDataCon]
87
88
89 -- TODO: Avoid using closure application for dictionaries.
90 -- vectExpr (_, AnnApp fn arg)
91 --  | if is application of dictionary 
92 --    just use regular app instead of closure app.
93
94 -- for lifted version. 
95 --      do liftPD (sub a dNumber)
96 --      lift the result of the selection, not sub and dNumber seprately. 
97
98 vectExpr (_, AnnApp fn arg)
99  = do
100       arg_ty' <- vectType arg_ty
101       res_ty' <- vectType res_ty
102
103       fn'     <- vectExpr fn
104       arg'    <- vectExpr arg
105
106       mkClosureApp arg_ty' res_ty' fn' arg'
107   where
108     (arg_ty, res_ty) = splitFunTy . exprType $ deAnnotate fn
109
110 vectExpr (_, AnnCase scrut bndr ty alts)
111   | Just (tycon, ty_args) <- splitTyConApp_maybe scrut_ty
112   , isAlgTyCon tycon
113   = vectAlgCase tycon ty_args scrut bndr ty alts
114   where
115     scrut_ty = exprType (deAnnotate scrut)
116
117 vectExpr (_, AnnLet (AnnNonRec bndr rhs) body)
118   = do
119       vrhs <- localV . inBind bndr . liftM snd $ vectPolyExpr False rhs
120       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
121       return $ vLet (vNonRec vbndr vrhs) vbody
122
123 vectExpr (_, AnnLet (AnnRec bs) body)
124   = do
125       (vbndrs, (vrhss, vbody)) <- vectBndrsIn bndrs
126                                 $ liftM2 (,)
127                                   (zipWithM vect_rhs bndrs rhss)
128                                   (vectExpr body)
129       return $ vLet (vRec vbndrs vrhss) vbody
130   where
131     (bndrs, rhss) = unzip bs
132
133     vect_rhs bndr rhs = localV
134                       . inBind bndr
135                       . liftM snd
136                       $ vectPolyExpr (isLoopBreaker $ idOccInfo bndr) rhs
137
138 vectExpr e@(_, AnnLam bndr _)
139   | isId bndr = liftM snd $ vectFnExpr True False e
140 {-
141 onlyIfV (isEmptyVarSet fvs) (vectScalarLam bs $ deAnnotate body)
142                 `orElseV` vectLam True fvs bs body
143   where
144     (bs,body) = collectAnnValBinders e
145 -}
146
147 vectExpr e = cantVectorise "Can't vectorise expression" (ppr $ deAnnotate e)
148
149
150 -- | Vectorise an expression with an outer lambda abstraction.
151 vectFnExpr 
152         :: Bool                 -- ^ When the RHS of a binding, whether that binding should be inlined.
153         -> Bool                 -- ^ Whether the binding is a loop breaker.
154         -> CoreExprWithFVs      -- ^ Expression to vectorise. Must have an outer `AnnLam`.
155         -> VM (Inline, VExpr)
156
157 vectFnExpr inline loop_breaker e@(fvs, AnnLam bndr _)
158   | isId bndr = onlyIfV (isEmptyVarSet fvs)
159                         (mark DontInline . vectScalarLam bs $ deAnnotate body)
160                 `orElseV` mark inlineMe (vectLam inline loop_breaker fvs bs body)
161   where
162     (bs,body) = collectAnnValBinders e
163
164 vectFnExpr _ _ e = mark DontInline $ vectExpr e
165
166 mark :: Inline -> VM a -> VM (Inline, a)
167 mark b p = do { x <- p; return (b,x) }
168
169
170 -- | Vectorise a function where are the args have scalar type,
171 --   that is Int, Float, Double etc.
172 vectScalarLam 
173         :: [Var]        -- ^ Bound variables of function.
174         -> CoreExpr     -- ^ Function body.
175         -> VM VExpr
176         
177 vectScalarLam args body
178  = do scalars <- globalScalars
179       onlyIfV (all is_scalar_ty arg_tys
180                && is_scalar_ty res_ty
181                && is_scalar (extendVarSetList scalars args) body
182                && uses scalars body)
183         $ do
184             fn_var  <- hoistExpr (fsLit "fn") (mkLams args body) DontInline
185             zipf    <- zipScalars arg_tys res_ty
186             clo     <- scalarClosure arg_tys res_ty (Var fn_var)
187                                                 (zipf `App` Var fn_var)
188             clo_var <- hoistExpr (fsLit "clo") clo DontInline
189             lclo    <- liftPD (Var clo_var)
190             return (Var clo_var, lclo)
191   where
192     arg_tys = map idType args
193     res_ty  = exprType body
194
195     is_scalar_ty ty 
196         | Just (tycon, [])   <- splitTyConApp_maybe ty
197         =    tycon == intTyCon
198           || tycon == floatTyCon
199           || tycon == doubleTyCon
200
201         | otherwise = False
202
203     is_scalar vs (Var v)     = v `elemVarSet` vs
204     is_scalar _ e@(Lit _)    = is_scalar_ty $ exprType e
205     is_scalar vs (App e1 e2) = is_scalar vs e1 && is_scalar vs e2
206     is_scalar _ _            = False
207
208     -- A scalar function has to actually compute something. Without the check,
209     -- we would treat (\(x :: Int) -> x) as a scalar function and lift it to
210     -- (map (\x -> x)) which is very bad. Normal lifting transforms it to
211     -- (\n# x -> x) which is what we want.
212     uses funs (Var v)     = v `elemVarSet` funs 
213     uses funs (App e1 e2) = uses funs e1 || uses funs e2
214     uses _ _              = False
215
216
217 -- | Vectorise a lambda abstraction.
218 vectLam 
219         :: Bool                 -- ^ When the RHS of a binding, whether that binding should be inlined.
220         -> Bool                 -- ^ Whether the binding is a loop breaker.
221         -> VarSet               -- ^ The free variables in the body.
222         -> [Var]                -- ^ Binding variables.
223         -> CoreExprWithFVs      -- ^ Body of abstraction.
224         -> VM VExpr
225
226 vectLam inline loop_breaker fvs bs body
227  = do tyvars    <- localTyVars
228       (vs, vvs) <- readLEnv $ \env ->
229                    unzip [(var, vv) | var <- varSetElems fvs
230                                     , Just vv <- [lookupVarEnv (local_vars env) var]]
231
232       arg_tys   <- mapM (vectType . idType) bs
233       res_ty    <- vectType (exprType $ deAnnotate body)
234
235       buildClosures tyvars vvs arg_tys res_ty
236         . hoistPolyVExpr tyvars (maybe_inline (length vs + length bs))
237         $ do
238             lc              <- builtin liftingContext
239             (vbndrs, vbody) <- vectBndrsIn (vs ++ bs) (vectExpr body)
240
241             vbody' <- break_loop lc res_ty vbody
242             return $ vLams lc vbndrs vbody'
243   where
244     maybe_inline n | inline    = Inline n
245                    | otherwise = DontInline
246
247     break_loop lc ty (ve, le)
248       | loop_breaker
249       = do
250           empty <- emptyPD ty
251           lty <- mkPDataType ty
252           return (ve, mkWildCase (Var lc) intPrimTy lty
253                         [(DEFAULT, [], le),
254                          (LitAlt (mkMachInt 0), [], empty)])
255
256       | otherwise = return (ve, le)
257  
258
259 vectTyAppExpr :: CoreExprWithFVs -> [Type] -> VM VExpr
260 vectTyAppExpr (_, AnnVar v) tys = vectPolyVar v tys
261 vectTyAppExpr e tys = cantVectorise "Can't vectorise expression"
262                         (ppr $ deAnnotate e `mkTyApps` tys)
263
264
265 -- | Vectorise an algebraic case expression.
266 --   We convert
267 --
268 --   case e :: t of v { ... }
269 --
270 -- to
271 --
272 --   V:    let v' = e in case v' of _ { ... }
273 --   L:    let v' = e in case v' `cast` ... of _ { ... }
274 --
275 --   When lifting, we have to do it this way because v must have the type
276 --   [:V(T):] but the scrutinee must be cast to the representation type. We also
277 --   have to handle the case where v is a wild var correctly.
278 --
279
280 -- FIXME: this is too lazy
281 vectAlgCase :: TyCon -> [Type] -> CoreExprWithFVs -> Var -> Type
282             -> [(AltCon, [Var], CoreExprWithFVs)]
283             -> VM VExpr
284 vectAlgCase _tycon _ty_args scrut bndr ty [(DEFAULT, [], body)]
285   = do
286       vscrut         <- vectExpr scrut
287       (vty, lty)     <- vectAndLiftType ty
288       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
289       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
290
291 vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt _, [], body)]
292   = do
293       vscrut         <- vectExpr scrut
294       (vty, lty)     <- vectAndLiftType ty
295       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
296       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
297
298 vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt dc, bndrs, body)]
299   = do
300       (vty, lty) <- vectAndLiftType ty
301       vexpr      <- vectExpr scrut
302       (vbndr, (vbndrs, (vect_body, lift_body)))
303          <- vect_scrut_bndr
304           . vectBndrsIn bndrs
305           $ vectExpr body
306       let (vect_bndrs, lift_bndrs) = unzip vbndrs
307       (vscrut, lscrut, pdata_tc, _arg_tys) <- mkVScrut (vVar vbndr)
308       vect_dc <- maybeV (lookupDataCon dc)
309       let [pdata_dc] = tyConDataCons pdata_tc
310
311       let vcase = mk_wild_case vscrut vty vect_dc  vect_bndrs vect_body
312           lcase = mk_wild_case lscrut lty pdata_dc lift_bndrs lift_body
313
314       return $ vLet (vNonRec vbndr vexpr) (vcase, lcase)
315   where
316     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
317                     | otherwise         = vectBndrIn bndr
318
319     mk_wild_case expr ty dc bndrs body
320       = mkWildCase expr (exprType expr) ty [(DataAlt dc, bndrs, body)]
321
322 vectAlgCase tycon _ty_args scrut bndr ty alts
323   = do
324       vect_tc     <- maybeV (lookupTyCon tycon)
325       (vty, lty)  <- vectAndLiftType ty
326
327       let arity = length (tyConDataCons vect_tc)
328       sel_ty <- builtin (selTy arity)
329       sel_bndr <- newLocalVar (fsLit "sel") sel_ty
330       let sel = Var sel_bndr
331
332       (vbndr, valts) <- vect_scrut_bndr
333                       $ mapM (proc_alt arity sel vty lty) alts'
334       let (vect_dcs, vect_bndrss, lift_bndrss, vbodies) = unzip4 valts
335
336       vexpr <- vectExpr scrut
337       (vect_scrut, lift_scrut, pdata_tc, _arg_tys) <- mkVScrut (vVar vbndr)
338       let [pdata_dc] = tyConDataCons pdata_tc
339
340       let (vect_bodies, lift_bodies) = unzip vbodies
341
342       vdummy <- newDummyVar (exprType vect_scrut)
343       ldummy <- newDummyVar (exprType lift_scrut)
344       let vect_case = Case vect_scrut vdummy vty
345                            (zipWith3 mk_vect_alt vect_dcs vect_bndrss vect_bodies)
346
347       lc <- builtin liftingContext
348       lbody <- combinePD vty (Var lc) sel lift_bodies
349       let lift_case = Case lift_scrut ldummy lty
350                            [(DataAlt pdata_dc, sel_bndr : concat lift_bndrss,
351                              lbody)]
352
353       return . vLet (vNonRec vbndr vexpr)
354              $ (vect_case, lift_case)
355   where
356     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
357                     | otherwise         = vectBndrIn bndr
358
359     alts' = sortBy (\(alt1, _, _) (alt2, _, _) -> cmp alt1 alt2) alts
360
361     cmp (DataAlt dc1) (DataAlt dc2) = dataConTag dc1 `compare` dataConTag dc2
362     cmp DEFAULT       DEFAULT       = EQ
363     cmp DEFAULT       _             = LT
364     cmp _             DEFAULT       = GT
365     cmp _             _             = panic "vectAlgCase/cmp"
366
367     proc_alt arity sel _ lty (DataAlt dc, bndrs, body)
368       = do
369           vect_dc <- maybeV (lookupDataCon dc)
370           let ntag = dataConTagZ vect_dc
371               tag  = mkDataConTag vect_dc
372               fvs  = freeVarsOf body `delVarSetList` bndrs
373
374           sel_tags  <- liftM (`App` sel) (builtin (selTags arity))
375           lc        <- builtin liftingContext
376           elems     <- builtin (selElements arity ntag)
377
378           (vbndrs, vbody)
379             <- vectBndrsIn bndrs
380              . localV
381              $ do
382                  binds    <- mapM (pack_var (Var lc) sel_tags tag)
383                            . filter isLocalId
384                            $ varSetElems fvs
385                  (ve, le) <- vectExpr body
386                  return (ve, Case (elems `App` sel) lc lty
387                              [(DEFAULT, [], (mkLets (concat binds) le))])
388                  -- empty    <- emptyPD vty
389                  -- return (ve, Case (elems `App` sel) lc lty
390                  --             [(DEFAULT, [], Let (NonRec flags_var flags_expr)
391                  --                             $ mkLets (concat binds) le),
392                  --               (LitAlt (mkMachInt 0), [], empty)])
393           let (vect_bndrs, lift_bndrs) = unzip vbndrs
394           return (vect_dc, vect_bndrs, lift_bndrs, vbody)
395
396     proc_alt _ _ _ _ _ = panic "vectAlgCase/proc_alt"
397
398     mk_vect_alt vect_dc bndrs body = (DataAlt vect_dc, bndrs, body)
399
400     pack_var len tags t v
401       = do
402           r <- lookupVar v
403           case r of
404             Local (vv, lv) ->
405               do
406                 lv'  <- cloneVar lv
407                 expr <- packByTagPD (idType vv) (Var lv) len tags t
408                 updLEnv (\env -> env { local_vars = extendVarEnv
409                                                 (local_vars env) v (vv, lv') })
410                 return [(NonRec lv' expr)]
411
412             _ -> return []
413