Fix Vectorise after introduction of MonadThings
[ghc-hetmet.git] / compiler / vectorise / Vectorise.hs
1
2 module Vectorise( vectorise )
3 where
4
5 import VectMonad
6 import VectUtils
7 import VectType
8 import VectCore
9
10 import DynFlags
11 import HscTypes hiding      ( MonadThings(..) )
12
13 import Module               ( dphSeqPackageId, dphParPackageId )
14 import CoreLint             ( showPass, endPass )
15 import CoreSyn
16 import CoreUtils
17 import CoreFVs
18 import SimplMonad           ( SimplCount, zeroSimplCount )
19 import Rules                ( RuleBase )
20 import DataCon
21 import TyCon
22 import Type
23 import FamInstEnv           ( extendFamInstEnvList )
24 import Var
25 import VarEnv
26 import VarSet
27 import Id
28 import OccName
29
30 import DsMonad
31
32 import Literal              ( Literal, mkMachInt )
33 import TysWiredIn
34
35 import Outputable
36 import FastString
37 import Control.Monad        ( liftM, liftM2, zipWithM )
38 import Data.List            ( sortBy, unzip4 )
39
40 vectorise :: DPHBackend -> HscEnv -> UniqSupply -> RuleBase -> ModGuts
41           -> IO (SimplCount, ModGuts)
42 vectorise backend hsc_env _ _ guts
43   = do
44       showPass dflags "Vectorisation"
45       eps <- hscEPS hsc_env
46       let info = hptVectInfo hsc_env `plusVectInfo` eps_vect_info eps
47       Just (info', guts') <- initV (backendPackage backend) hsc_env guts info
48                                    (vectModule guts)
49       endPass dflags "Vectorisation" Opt_D_dump_vect (mg_binds guts')
50       return (zeroSimplCount dflags, guts' { mg_vect_info = info' })
51   where
52     dflags = hsc_dflags hsc_env
53
54     backendPackage DPHSeq  = dphSeqPackageId
55     backendPackage DPHPar  = dphParPackageId
56
57 vectModule :: ModGuts -> VM ModGuts
58 vectModule guts
59   = do
60       (types', fam_insts, tc_binds) <- vectTypeEnv (mg_types guts)
61
62       let fam_inst_env' = extendFamInstEnvList (mg_fam_inst_env guts) fam_insts
63       updGEnv (setFamInstEnv fam_inst_env')
64
65       -- dicts   <- mapM buildPADict pa_insts
66       -- workers <- mapM vectDataConWorkers pa_insts
67       binds'  <- mapM vectTopBind (mg_binds guts)
68       return $ guts { mg_types        = types'
69                     , mg_binds        = Rec tc_binds : binds'
70                     , mg_fam_inst_env = fam_inst_env'
71                     , mg_fam_insts    = mg_fam_insts guts ++ fam_insts
72                     }
73
74 vectTopBind :: CoreBind -> VM CoreBind
75 vectTopBind b@(NonRec var expr)
76   = do
77       var'  <- vectTopBinder var
78       expr' <- vectTopRhs var expr
79       hs    <- takeHoisted
80       cexpr <- tryConvert var var' expr
81       return . Rec $ (var, cexpr) : (var', expr') : hs
82   `orElseV`
83     return b
84
85 vectTopBind b@(Rec bs)
86   = do
87       vars'  <- mapM vectTopBinder vars
88       exprs' <- zipWithM vectTopRhs vars exprs
89       hs     <- takeHoisted
90       cexprs <- sequence $ zipWith3 tryConvert vars vars' exprs
91       return . Rec $ zip vars cexprs ++ zip vars' exprs' ++ hs
92   `orElseV`
93     return b
94   where
95     (vars, exprs) = unzip bs
96
97 vectTopBinder :: Var -> VM Var
98 vectTopBinder var
99   = do
100       vty  <- vectType (idType var)
101       var' <- cloneId mkVectOcc var vty
102       defGlobalVar var var'
103       return var'
104
105 vectTopRhs :: Var -> CoreExpr -> VM CoreExpr
106 vectTopRhs var expr
107   = do
108       closedV . liftM vectorised
109               . inBind var
110               $ vectPolyExpr (freeVars expr)
111
112 tryConvert :: Var -> Var -> CoreExpr -> VM CoreExpr
113 tryConvert var vect_var rhs
114   = fromVect (idType var) (Var vect_var) `orElseV` return rhs
115
116 -- ----------------------------------------------------------------------------
117 -- Bindings
118
119 vectBndr :: Var -> VM VVar
120 vectBndr v
121   = do
122       (vty, lty) <- vectAndLiftType (idType v)
123       let vv = v `Id.setIdType` vty
124           lv = v `Id.setIdType` lty
125       updLEnv (mapTo vv lv)
126       return (vv, lv)
127   where
128     mapTo vv lv env = env { local_vars = extendVarEnv (local_vars env) v (vv, lv) }
129
130 vectBndrNew :: Var -> FastString -> VM VVar
131 vectBndrNew v fs
132   = do
133       vty <- vectType (idType v)
134       vv  <- newLocalVVar fs vty
135       updLEnv (upd vv)
136       return vv
137   where
138     upd vv env = env { local_vars = extendVarEnv (local_vars env) v vv }
139
140 vectBndrIn :: Var -> VM a -> VM (VVar, a)
141 vectBndrIn v p
142   = localV
143   $ do
144       vv <- vectBndr v
145       x <- p
146       return (vv, x)
147
148 vectBndrNewIn :: Var -> FastString -> VM a -> VM (VVar, a)
149 vectBndrNewIn v fs p
150   = localV
151   $ do
152       vv <- vectBndrNew v fs
153       x  <- p
154       return (vv, x)
155
156 vectBndrsIn :: [Var] -> VM a -> VM ([VVar], a)
157 vectBndrsIn vs p
158   = localV
159   $ do
160       vvs <- mapM vectBndr vs
161       x <- p
162       return (vvs, x)
163
164 -- ----------------------------------------------------------------------------
165 -- Expressions
166
167 vectVar :: Var -> VM VExpr
168 vectVar v
169   = do
170       r <- lookupVar v
171       case r of
172         Local (vv,lv) -> return (Var vv, Var lv)
173         Global vv     -> do
174                            let vexpr = Var vv
175                            lexpr <- liftPA vexpr
176                            return (vexpr, lexpr)
177
178 vectPolyVar :: Var -> [Type] -> VM VExpr
179 vectPolyVar v tys
180   = do
181       vtys <- mapM vectType tys
182       r <- lookupVar v
183       case r of
184         Local (vv, lv) -> liftM2 (,) (polyApply (Var vv) vtys)
185                                      (polyApply (Var lv) vtys)
186         Global poly    -> do
187                             vexpr <- polyApply (Var poly) vtys
188                             lexpr <- liftPA vexpr
189                             return (vexpr, lexpr)
190
191 vectLiteral :: Literal -> VM VExpr
192 vectLiteral lit
193   = do
194       lexpr <- liftPA (Lit lit)
195       return (Lit lit, lexpr)
196
197 vectPolyExpr :: CoreExprWithFVs -> VM VExpr
198 vectPolyExpr (_, AnnNote note expr)
199   = liftM (vNote note) $ vectPolyExpr expr
200 vectPolyExpr expr
201   = polyAbstract tvs $ \abstract ->
202     do
203       mono' <- vectExpr mono
204       return $ mapVect abstract mono'
205   where
206     (tvs, mono) = collectAnnTypeBinders expr
207
208 vectExpr :: CoreExprWithFVs -> VM VExpr
209 vectExpr (_, AnnType ty)
210   = liftM vType (vectType ty)
211
212 vectExpr (_, AnnVar v) = vectVar v
213
214 vectExpr (_, AnnLit lit) = vectLiteral lit
215
216 vectExpr (_, AnnNote note expr)
217   = liftM (vNote note) (vectExpr expr)
218
219 vectExpr e@(_, AnnApp _ arg)
220   | isAnnTypeArg arg
221   = vectTyAppExpr fn tys
222   where
223     (fn, tys) = collectAnnTypeArgs e
224
225 vectExpr (_, AnnApp (_, AnnVar v) (_, AnnLit lit))
226   | Just con <- isDataConId_maybe v
227   , is_special_con con
228   = do
229       let vexpr = App (Var v) (Lit lit)
230       lexpr <- liftPA vexpr
231       return (vexpr, lexpr)
232   where
233     is_special_con con = con `elem` [intDataCon, floatDataCon, doubleDataCon]
234
235
236 vectExpr (_, AnnApp fn arg)
237   = do
238       arg_ty' <- vectType arg_ty
239       res_ty' <- vectType res_ty
240       fn'     <- vectExpr fn
241       arg'    <- vectExpr arg
242       mkClosureApp arg_ty' res_ty' fn' arg'
243   where
244     (arg_ty, res_ty) = splitFunTy . exprType $ deAnnotate fn
245
246 vectExpr (_, AnnCase scrut bndr ty alts)
247   | Just (tycon, ty_args) <- splitTyConApp_maybe scrut_ty
248   , isAlgTyCon tycon
249   = vectAlgCase tycon ty_args scrut bndr ty alts
250   where
251     scrut_ty = exprType (deAnnotate scrut)
252
253 vectExpr (_, AnnCase _ _ _ _)
254   = panic "vectExpr: case"
255
256 vectExpr (_, AnnLet (AnnNonRec bndr rhs) body)
257   = do
258       vrhs <- localV . inBind bndr $ vectPolyExpr rhs
259       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
260       return $ vLet (vNonRec vbndr vrhs) vbody
261
262 vectExpr (_, AnnLet (AnnRec bs) body)
263   = do
264       (vbndrs, (vrhss, vbody)) <- vectBndrsIn bndrs
265                                 $ liftM2 (,)
266                                   (zipWithM vect_rhs bndrs rhss)
267                                   (vectPolyExpr body)
268       return $ vLet (vRec vbndrs vrhss) vbody
269   where
270     (bndrs, rhss) = unzip bs
271
272     vect_rhs bndr rhs = localV
273                       . inBind bndr
274                       $ vectExpr rhs
275
276 vectExpr e@(fvs, AnnLam bndr _)
277   | not (isId bndr) = pprPanic "vectExpr" (ppr $ deAnnotate e)
278   | otherwise = vectLam fvs bs body
279   where
280     (bs,body) = collectAnnValBinders e
281
282 vectExpr e = pprPanic "vectExpr" (ppr $ deAnnotate e)
283
284 vectLam :: VarSet -> [Var] -> CoreExprWithFVs -> VM VExpr
285 vectLam fvs bs body
286   = do
287       tyvars <- localTyVars
288       (vs, vvs) <- readLEnv $ \env ->
289                    unzip [(var, vv) | var <- varSetElems fvs
290                                     , Just vv <- [lookupVarEnv (local_vars env) var]]
291
292       arg_tys <- mapM (vectType . idType) bs
293       res_ty  <- vectType (exprType $ deAnnotate body)
294
295       buildClosures tyvars vvs arg_tys res_ty
296         . hoistPolyVExpr tyvars
297         $ do
298             lc <- builtin liftingContext
299             (vbndrs, vbody) <- vectBndrsIn (vs ++ bs)
300                                            (vectExpr body)
301             return $ vLams lc vbndrs vbody
302
303 vectTyAppExpr :: CoreExprWithFVs -> [Type] -> VM VExpr
304 vectTyAppExpr (_, AnnVar v) tys = vectPolyVar v tys
305 vectTyAppExpr e _ = pprPanic "vectTyAppExpr" (ppr $ deAnnotate e)
306
307 -- We convert
308 --
309 --   case e :: t of v { ... }
310 --
311 -- to
312 --
313 --   V:    let v' = e in case v' of _ { ... }
314 --   L:    let v' = e in case v' `cast` ... of _ { ... }
315 --
316 -- When lifting, we have to do it this way because v must have the type
317 -- [:V(T):] but the scrutinee must be cast to the representation type. We also
318 -- have to handle the case where v is a wild var correctly.
319 --
320
321 -- FIXME: this is too lazy
322 vectAlgCase :: TyCon -> [Type] -> CoreExprWithFVs -> Var -> Type
323             -> [(AltCon, [Var], CoreExprWithFVs)]
324             -> VM VExpr
325 vectAlgCase _tycon _ty_args scrut bndr ty [(DEFAULT, [], body)]
326   = do
327       vscrut         <- vectExpr scrut
328       (vty, lty)     <- vectAndLiftType ty
329       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
330       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
331
332 vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt _, [], body)]
333   = do
334       vscrut         <- vectExpr scrut
335       (vty, lty)     <- vectAndLiftType ty
336       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
337       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
338
339 vectAlgCase tycon _ty_args scrut bndr ty [(DataAlt dc, bndrs, body)]
340   = do
341       vect_tc    <- maybeV (lookupTyCon tycon)
342       (vty, lty) <- vectAndLiftType ty
343       vexpr      <- vectExpr scrut
344       (vbndr, (vbndrs, vbody)) <- vect_scrut_bndr
345                                 . vectBndrsIn bndrs
346                                 $ vectExpr body
347
348       (vscrut, arr_tc, _arg_tys) <- mkVScrut (vVar vbndr)
349       vect_dc <- maybeV (lookupDataCon dc)
350       let [arr_dc] = tyConDataCons arr_tc
351       repr <- mkRepr vect_tc
352       shape_bndrs <- arrShapeVars repr
353       return . vLet (vNonRec vbndr vexpr)
354              $ vCaseProd vscrut vty lty vect_dc arr_dc shape_bndrs vbndrs vbody
355   where
356     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
357                     | otherwise         = vectBndrIn bndr
358
359 vectAlgCase tycon _ty_args scrut bndr ty alts
360   = do
361       vect_tc     <- maybeV (lookupTyCon tycon)
362       (vty, lty)  <- vectAndLiftType ty
363       repr        <- mkRepr vect_tc
364       shape_bndrs <- arrShapeVars repr
365       (len, sel, indices) <- arrSelector repr (map Var shape_bndrs)
366
367       (vbndr, valts) <- vect_scrut_bndr $ mapM (proc_alt sel vty lty) alts'
368       let (vect_dcs, vect_bndrss, lift_bndrss, vbodies) = unzip4 valts
369
370       vexpr <- vectExpr scrut
371       (vscrut, arr_tc, _arg_tys) <- mkVScrut (vVar vbndr)
372       let [arr_dc] = tyConDataCons arr_tc
373
374       let (vect_scrut,  lift_scrut)  = vscrut
375           (vect_bodies, lift_bodies) = unzip vbodies
376
377       let vect_case = Case vect_scrut (mkWildId (exprType vect_scrut)) vty
378                            (zipWith3 mk_vect_alt vect_dcs vect_bndrss vect_bodies)
379
380       lbody <- combinePA vty len sel indices lift_bodies
381       let lift_case = Case lift_scrut (mkWildId (exprType lift_scrut)) lty
382                            [(DataAlt arr_dc, shape_bndrs ++ concat lift_bndrss,
383                              lbody)]
384
385       return . vLet (vNonRec vbndr vexpr)
386              $ (vect_case, lift_case)
387   where
388     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
389                     | otherwise         = vectBndrIn bndr
390
391     alts' = sortBy (\(alt1, _, _) (alt2, _, _) -> cmp alt1 alt2) alts
392
393     cmp (DataAlt dc1) (DataAlt dc2) = dataConTag dc1 `compare` dataConTag dc2
394     cmp DEFAULT       DEFAULT       = EQ
395     cmp DEFAULT       _             = LT
396     cmp _             DEFAULT       = GT
397     cmp _             _             = panic "vectAlgCase/cmp"
398
399     proc_alt sel vty lty (DataAlt dc, bndrs, body)
400       = do
401           vect_dc <- maybeV (lookupDataCon dc)
402           let tag = mkDataConTag vect_dc
403               fvs = freeVarsOf body `delVarSetList` bndrs
404           (vect_bndrs, lift_bndrs, vbody)
405             <- vect_alt_bndrs bndrs
406              $ \len -> packLiftingContext len sel tag fvs vty lty
407              $ vectExpr body
408
409           return (vect_dc, vect_bndrs, lift_bndrs, vbody)
410     proc_alt _ _ _ _ = panic "vectAlgCase/proc_alt"
411
412     vect_alt_bndrs [] p
413       = do
414           void_tc <- builtin voidTyCon
415           let void_ty = mkTyConApp void_tc []
416           arr_ty <- mkPArrayType void_ty
417           bndr   <- newLocalVar (fsLit "voids") arr_ty
418           len    <- lengthPA void_ty (Var bndr)
419           e      <- p len
420           return ([], [bndr], e)
421
422     vect_alt_bndrs bndrs p
423        = localV
424        $ do
425            vbndrs <- mapM vectBndr bndrs
426            let (vect_bndrs, lift_bndrs) = unzip vbndrs
427                vv : _ = vect_bndrs
428                lv : _ = lift_bndrs
429            len <- lengthPA (idType vv) (Var lv)
430            e   <- p len
431            return (vect_bndrs, lift_bndrs, e)
432
433     mk_vect_alt vect_dc bndrs body = (DataAlt vect_dc, bndrs, body)
434
435 packLiftingContext :: CoreExpr -> CoreExpr -> CoreExpr -> VarSet
436                    -> Type -> Type -> VM VExpr -> VM VExpr
437 packLiftingContext len shape tag fvs vty lty p
438   = do
439       select <- builtin selectPAIntPrimVar
440       let sel_expr = mkApps (Var select) [shape, tag]
441       sel_var <- newLocalVar (fsLit "sel#") (exprType sel_expr)
442       lc_var <- builtin liftingContext
443       localV $
444         do
445           bnds <- mapM (packFreeVar (Var lc_var) (Var sel_var))
446                 . filter isLocalId
447                 $ varSetElems fvs
448           (vexpr, lexpr) <- p
449           empty <- emptyPA vty
450           return (vexpr, Let (NonRec sel_var sel_expr)
451                          $ Case len lc_var lty
452                              [(DEFAULT, [], mkLets (concat bnds) lexpr),
453                               (LitAlt (mkMachInt 0), [], empty)])
454
455 packFreeVar :: CoreExpr -> CoreExpr -> Var -> VM [CoreBind]
456 packFreeVar len sel v
457   = do
458       r <- lookupVar v
459       case r of
460         Local (vv,lv) ->
461           do
462             lv' <- cloneVar lv
463             expr <- packPA (idType vv) (Var lv) len sel
464             updLEnv (upd vv lv')
465             return [(NonRec lv' expr)]
466
467         _  -> return []
468   where
469     upd vv lv' env = env { local_vars = extendVarEnv (local_vars env) v (vv, lv') }
470