Don't panic on non-vectorisable expressions
[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 (_, AnnLet (AnnNonRec bndr rhs) body)
254   = do
255       vrhs <- localV . inBind bndr $ vectPolyExpr rhs
256       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
257       return $ vLet (vNonRec vbndr vrhs) vbody
258
259 vectExpr (_, AnnLet (AnnRec bs) body)
260   = do
261       (vbndrs, (vrhss, vbody)) <- vectBndrsIn bndrs
262                                 $ liftM2 (,)
263                                   (zipWithM vect_rhs bndrs rhss)
264                                   (vectPolyExpr body)
265       return $ vLet (vRec vbndrs vrhss) vbody
266   where
267     (bndrs, rhss) = unzip bs
268
269     vect_rhs bndr rhs = localV
270                       . inBind bndr
271                       $ vectExpr rhs
272
273 vectExpr e@(fvs, AnnLam bndr _)
274   | isId bndr = vectLam fvs bs body
275   where
276     (bs,body) = collectAnnValBinders e
277
278 vectExpr e = traceNoV "vectExpr: can't vectorise" (ppr $ deAnnotate e)
279
280 vectLam :: VarSet -> [Var] -> CoreExprWithFVs -> VM VExpr
281 vectLam fvs bs body
282   = do
283       tyvars <- localTyVars
284       (vs, vvs) <- readLEnv $ \env ->
285                    unzip [(var, vv) | var <- varSetElems fvs
286                                     , Just vv <- [lookupVarEnv (local_vars env) var]]
287
288       arg_tys <- mapM (vectType . idType) bs
289       res_ty  <- vectType (exprType $ deAnnotate body)
290
291       buildClosures tyvars vvs arg_tys res_ty
292         . hoistPolyVExpr tyvars
293         $ do
294             lc <- builtin liftingContext
295             (vbndrs, vbody) <- vectBndrsIn (vs ++ bs)
296                                            (vectExpr body)
297             return $ vLams lc vbndrs vbody
298
299 vectTyAppExpr :: CoreExprWithFVs -> [Type] -> VM VExpr
300 vectTyAppExpr (_, AnnVar v) tys = vectPolyVar v tys
301 vectTyAppExpr e _ = traceNoV "vectTyAppExpr: can't vectorise" (ppr $ deAnnotate e)
302
303 -- We convert
304 --
305 --   case e :: t of v { ... }
306 --
307 -- to
308 --
309 --   V:    let v' = e in case v' of _ { ... }
310 --   L:    let v' = e in case v' `cast` ... of _ { ... }
311 --
312 -- When lifting, we have to do it this way because v must have the type
313 -- [:V(T):] but the scrutinee must be cast to the representation type. We also
314 -- have to handle the case where v is a wild var correctly.
315 --
316
317 -- FIXME: this is too lazy
318 vectAlgCase :: TyCon -> [Type] -> CoreExprWithFVs -> Var -> Type
319             -> [(AltCon, [Var], CoreExprWithFVs)]
320             -> VM VExpr
321 vectAlgCase _tycon _ty_args scrut bndr ty [(DEFAULT, [], body)]
322   = do
323       vscrut         <- vectExpr scrut
324       (vty, lty)     <- vectAndLiftType ty
325       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
326       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
327
328 vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt _, [], body)]
329   = do
330       vscrut         <- vectExpr scrut
331       (vty, lty)     <- vectAndLiftType ty
332       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
333       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
334
335 vectAlgCase tycon _ty_args scrut bndr ty [(DataAlt dc, bndrs, body)]
336   = do
337       vect_tc    <- maybeV (lookupTyCon tycon)
338       (vty, lty) <- vectAndLiftType ty
339       vexpr      <- vectExpr scrut
340       (vbndr, (vbndrs, vbody)) <- vect_scrut_bndr
341                                 . vectBndrsIn bndrs
342                                 $ vectExpr body
343
344       (vscrut, arr_tc, _arg_tys) <- mkVScrut (vVar vbndr)
345       vect_dc <- maybeV (lookupDataCon dc)
346       let [arr_dc] = tyConDataCons arr_tc
347       repr <- mkRepr vect_tc
348       shape_bndrs <- arrShapeVars repr
349       return . vLet (vNonRec vbndr vexpr)
350              $ vCaseProd vscrut vty lty vect_dc arr_dc shape_bndrs vbndrs vbody
351   where
352     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
353                     | otherwise         = vectBndrIn bndr
354
355 vectAlgCase tycon _ty_args scrut bndr ty alts
356   = do
357       vect_tc     <- maybeV (lookupTyCon tycon)
358       (vty, lty)  <- vectAndLiftType ty
359       repr        <- mkRepr vect_tc
360       shape_bndrs <- arrShapeVars repr
361       (len, sel, indices) <- arrSelector repr (map Var shape_bndrs)
362
363       (vbndr, valts) <- vect_scrut_bndr $ mapM (proc_alt sel vty lty) alts'
364       let (vect_dcs, vect_bndrss, lift_bndrss, vbodies) = unzip4 valts
365
366       vexpr <- vectExpr scrut
367       (vscrut, arr_tc, _arg_tys) <- mkVScrut (vVar vbndr)
368       let [arr_dc] = tyConDataCons arr_tc
369
370       let (vect_scrut,  lift_scrut)  = vscrut
371           (vect_bodies, lift_bodies) = unzip vbodies
372
373       let vect_case = Case vect_scrut (mkWildId (exprType vect_scrut)) vty
374                            (zipWith3 mk_vect_alt vect_dcs vect_bndrss vect_bodies)
375
376       lbody <- combinePA vty len sel indices lift_bodies
377       let lift_case = Case lift_scrut (mkWildId (exprType lift_scrut)) lty
378                            [(DataAlt arr_dc, shape_bndrs ++ concat lift_bndrss,
379                              lbody)]
380
381       return . vLet (vNonRec vbndr vexpr)
382              $ (vect_case, lift_case)
383   where
384     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
385                     | otherwise         = vectBndrIn bndr
386
387     alts' = sortBy (\(alt1, _, _) (alt2, _, _) -> cmp alt1 alt2) alts
388
389     cmp (DataAlt dc1) (DataAlt dc2) = dataConTag dc1 `compare` dataConTag dc2
390     cmp DEFAULT       DEFAULT       = EQ
391     cmp DEFAULT       _             = LT
392     cmp _             DEFAULT       = GT
393     cmp _             _             = panic "vectAlgCase/cmp"
394
395     proc_alt sel vty lty (DataAlt dc, bndrs, body)
396       = do
397           vect_dc <- maybeV (lookupDataCon dc)
398           let tag = mkDataConTag vect_dc
399               fvs = freeVarsOf body `delVarSetList` bndrs
400           (vect_bndrs, lift_bndrs, vbody)
401             <- vect_alt_bndrs bndrs
402              $ \len -> packLiftingContext len sel tag fvs vty lty
403              $ vectExpr body
404
405           return (vect_dc, vect_bndrs, lift_bndrs, vbody)
406     proc_alt _ _ _ _ = panic "vectAlgCase/proc_alt"
407
408     vect_alt_bndrs [] p
409       = do
410           void_tc <- builtin voidTyCon
411           let void_ty = mkTyConApp void_tc []
412           arr_ty <- mkPArrayType void_ty
413           bndr   <- newLocalVar (fsLit "voids") arr_ty
414           len    <- lengthPA void_ty (Var bndr)
415           e      <- p len
416           return ([], [bndr], e)
417
418     vect_alt_bndrs bndrs p
419        = localV
420        $ do
421            vbndrs <- mapM vectBndr bndrs
422            let (vect_bndrs, lift_bndrs) = unzip vbndrs
423                vv : _ = vect_bndrs
424                lv : _ = lift_bndrs
425            len <- lengthPA (idType vv) (Var lv)
426            e   <- p len
427            return (vect_bndrs, lift_bndrs, e)
428
429     mk_vect_alt vect_dc bndrs body = (DataAlt vect_dc, bndrs, body)
430
431 packLiftingContext :: CoreExpr -> CoreExpr -> CoreExpr -> VarSet
432                    -> Type -> Type -> VM VExpr -> VM VExpr
433 packLiftingContext len shape tag fvs vty lty p
434   = do
435       select <- builtin selectPAIntPrimVar
436       let sel_expr = mkApps (Var select) [shape, tag]
437       sel_var <- newLocalVar (fsLit "sel#") (exprType sel_expr)
438       lc_var <- builtin liftingContext
439       localV $
440         do
441           bnds <- mapM (packFreeVar (Var lc_var) (Var sel_var))
442                 . filter isLocalId
443                 $ varSetElems fvs
444           (vexpr, lexpr) <- p
445           empty <- emptyPA vty
446           return (vexpr, Let (NonRec sel_var sel_expr)
447                          $ Case len lc_var lty
448                              [(DEFAULT, [], mkLets (concat bnds) lexpr),
449                               (LitAlt (mkMachInt 0), [], empty)])
450
451 packFreeVar :: CoreExpr -> CoreExpr -> Var -> VM [CoreBind]
452 packFreeVar len sel v
453   = do
454       r <- lookupVar v
455       case r of
456         Local (vv,lv) ->
457           do
458             lv' <- cloneVar lv
459             expr <- packPA (idType vv) (Var lv) len sel
460             updLEnv (upd vv lv')
461             return [(NonRec lv' expr)]
462
463         _  -> return []
464   where
465     upd vv lv' env = env { local_vars = extendVarEnv (local_vars env) v (vv, lv') }
466