8dccd61c2412f525da46badd5404ce02bcb26b27
[ghc-hetmet.git] / compiler / vectorise / VectUtils.hs
1 module VectUtils (
2   collectAnnTypeBinders, collectAnnTypeArgs, isAnnTypeArg,
3   collectAnnValBinders,
4   dataConTagZ, mkDataConTag, mkDataConTagLit,
5
6   newLocalVVar,
7
8   mkBuiltinCo, voidType, mkWrapType,
9   mkPADictType, mkPArrayType, mkPDataType, mkPReprType, mkPArray,
10
11   pdataReprTyCon, pdataReprDataCon, mkVScrut,
12   prDictOfType, prDFunOfTyCon,
13   paDictArgType, paDictOfType, paDFunType,
14   paMethod, wrapPR, replicatePD, emptyPD, packByTagPD,
15   combinePD,
16   liftPD,
17   zipScalars, scalarClosure,
18   polyAbstract, polyApply, polyVApply, polyArity,
19   Inline(..), addInlineArity, inlineMe,
20   hoistBinding, hoistExpr, hoistPolyVExpr, takeHoisted,
21   buildClosure, buildClosures,
22   mkClosureApp
23 ) where
24
25 import VectCore
26 import VectMonad
27
28 import MkCore ( mkCoreTup, mkWildCase )
29 import CoreSyn
30 import CoreUtils
31 import CoreUnfold         ( mkInlineRule )
32 import Coercion
33 import Type
34 import TypeRep
35 import TyCon
36 import DataCon
37 import Var
38 import MkId               ( unwrapFamInstScrut )
39 import Id                 ( setIdUnfolding )
40 import TysWiredIn
41 import BasicTypes         ( Boxity(..) )
42 import Literal            ( Literal, mkMachInt )
43
44 import Outputable
45 import FastString
46
47 import Control.Monad
48
49 collectAnnTypeArgs :: AnnExpr b ann -> (AnnExpr b ann, [Type])
50 collectAnnTypeArgs expr = go expr []
51   where
52     go (_, AnnApp f (_, AnnType ty)) tys = go f (ty : tys)
53     go e                             tys = (e, tys)
54
55 collectAnnTypeBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
56 collectAnnTypeBinders expr = go [] expr
57   where
58     go bs (_, AnnLam b e) | isTyVar b = go (b:bs) e
59     go bs e                           = (reverse bs, e)
60
61 collectAnnValBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
62 collectAnnValBinders expr = go [] expr
63   where
64     go bs (_, AnnLam b e) | isId b = go (b:bs) e
65     go bs e                        = (reverse bs, e)
66
67 isAnnTypeArg :: AnnExpr b ann -> Bool
68 isAnnTypeArg (_, AnnType _) = True
69 isAnnTypeArg _              = False
70
71 dataConTagZ :: DataCon -> Int
72 dataConTagZ con = dataConTag con - fIRST_TAG
73
74 mkDataConTagLit :: DataCon -> Literal
75 mkDataConTagLit = mkMachInt . toInteger . dataConTagZ
76
77 mkDataConTag :: DataCon -> CoreExpr
78 mkDataConTag = mkIntLitInt . dataConTagZ
79
80 splitPrimTyCon :: Type -> Maybe TyCon
81 splitPrimTyCon ty
82   | Just (tycon, []) <- splitTyConApp_maybe ty
83   , isPrimTyCon tycon
84   = Just tycon
85
86   | otherwise = Nothing
87
88 mkBuiltinTyConApp :: (Builtins -> TyCon) -> [Type] -> VM Type
89 mkBuiltinTyConApp get_tc tys
90   = do
91       tc <- builtin get_tc
92       return $ mkTyConApp tc tys
93
94 mkBuiltinTyConApps :: (Builtins -> TyCon) -> [Type] -> Type -> VM Type
95 mkBuiltinTyConApps get_tc tys ty
96   = do
97       tc <- builtin get_tc
98       return $ foldr (mk tc) ty tys
99   where
100     mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2]
101
102 voidType :: VM Type
103 voidType = mkBuiltinTyConApp VectMonad.voidTyCon []
104
105 mkWrapType :: Type -> VM Type
106 mkWrapType ty = mkBuiltinTyConApp wrapTyCon [ty]
107
108 mkClosureTypes :: [Type] -> Type -> VM Type
109 mkClosureTypes = mkBuiltinTyConApps closureTyCon
110
111 mkPReprType :: Type -> VM Type
112 mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty]
113
114 mkPADictType :: Type -> VM Type
115 mkPADictType ty = mkBuiltinTyConApp paTyCon [ty]
116
117 mkPArrayType :: Type -> VM Type
118 mkPArrayType ty
119   | Just tycon <- splitPrimTyCon ty
120   = do
121       r <- lookupPrimPArray tycon
122       case r of
123         Just arr -> return $ mkTyConApp arr []
124         Nothing  -> cantVectorise "Primitive tycon not vectorised" (ppr tycon)
125 mkPArrayType ty = mkBuiltinTyConApp parrayTyCon [ty]
126
127 mkPDataType :: Type -> VM Type
128 mkPDataType ty = mkBuiltinTyConApp pdataTyCon [ty]
129
130 mkPArray :: Type -> CoreExpr -> CoreExpr -> VM CoreExpr
131 mkPArray ty len dat = do
132                         tc <- builtin parrayTyCon
133                         let [dc] = tyConDataCons tc
134                         return $ mkConApp dc [Type ty, len, dat]
135
136 mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion
137 mkBuiltinCo get_tc
138   = do
139       tc <- builtin get_tc
140       return $ mkTyConApp tc []
141
142 pdataReprTyCon :: Type -> VM (TyCon, [Type])
143 pdataReprTyCon ty = builtin pdataTyCon >>= (`lookupFamInst` [ty])
144
145 pdataReprDataCon :: Type -> VM (DataCon, [Type])
146 pdataReprDataCon ty
147   = do
148       (tc, arg_tys) <- pdataReprTyCon ty
149       let [dc] = tyConDataCons tc
150       return (dc, arg_tys)
151
152 mkVScrut :: VExpr -> VM (CoreExpr, CoreExpr, TyCon, [Type])
153 mkVScrut (ve, le)
154   = do
155       (tc, arg_tys) <- pdataReprTyCon ty
156       return (ve, unwrapFamInstScrut tc arg_tys le, tc, arg_tys)
157   where
158     ty = exprType ve
159
160 prDFunOfTyCon :: TyCon -> VM CoreExpr
161 prDFunOfTyCon tycon
162   = liftM Var
163   . maybeCantVectoriseM "No PR dictionary for tycon" (ppr tycon)
164   $ lookupTyConPR tycon
165
166 paDictArgType :: TyVar -> VM (Maybe Type)
167 paDictArgType tv = go (TyVarTy tv) (tyVarKind tv)
168   where
169     go ty k | Just k' <- kindView k = go ty k'
170     go ty (FunTy k1 k2)
171       = do
172           tv   <- newTyVar (fsLit "a") k1
173           mty1 <- go (TyVarTy tv) k1
174           case mty1 of
175             Just ty1 -> do
176                           mty2 <- go (AppTy ty (TyVarTy tv)) k2
177                           return $ fmap (ForAllTy tv . FunTy ty1) mty2
178             Nothing  -> go ty k2
179
180     go ty k
181       | isLiftedTypeKind k
182       = liftM Just (mkPADictType ty)
183
184     go _ _ = return Nothing
185
186 paDictOfType :: Type -> VM CoreExpr
187 paDictOfType ty = paDictOfTyApp ty_fn ty_args
188   where
189     (ty_fn, ty_args) = splitAppTys ty
190
191 paDictOfTyApp :: Type -> [Type] -> VM CoreExpr
192 paDictOfTyApp ty_fn ty_args
193   | Just ty_fn' <- coreView ty_fn = paDictOfTyApp ty_fn' ty_args
194 paDictOfTyApp (TyVarTy tv) ty_args
195   = do
196       dfun <- maybeV (lookupTyVarPA tv)
197       paDFunApply dfun ty_args
198 paDictOfTyApp (TyConApp tc _) ty_args
199   = do
200       dfun <- maybeCantVectoriseM "No PA dictionary for tycon" (ppr tc)
201             $ lookupTyConPA tc
202       paDFunApply (Var dfun) ty_args
203 paDictOfTyApp ty _
204   = cantVectorise "Can't construct PA dictionary for type" (ppr ty)
205
206 paDFunType :: TyCon -> VM Type
207 paDFunType tc
208   = do
209       margs <- mapM paDictArgType tvs
210       res   <- mkPADictType (mkTyConApp tc arg_tys)
211       return . mkForAllTys tvs
212              $ mkFunTys [arg | Just arg <- margs] res
213   where
214     tvs = tyConTyVars tc
215     arg_tys = mkTyVarTys tvs
216
217 paDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
218 paDFunApply dfun tys
219   = do
220       dicts <- mapM paDictOfType tys
221       return $ mkApps (mkTyApps dfun tys) dicts
222
223 paMethod :: (Builtins -> Var) -> String -> Type -> VM CoreExpr
224 paMethod _ name ty
225   | Just tycon <- splitPrimTyCon ty
226   = liftM Var
227   . maybeCantVectoriseM "No PA method" (text name <+> text "for" <+> ppr tycon)
228   $ lookupPrimMethod tycon name
229
230 paMethod method _ ty
231   = do
232       fn   <- builtin method
233       dict <- paDictOfType ty
234       return $ mkApps (Var fn) [Type ty, dict]
235
236 prDictOfType :: Type -> VM CoreExpr
237 prDictOfType ty = prDictOfTyApp ty_fn ty_args
238   where
239     (ty_fn, ty_args) = splitAppTys ty
240
241 prDictOfTyApp :: Type -> [Type] -> VM CoreExpr
242 prDictOfTyApp ty_fn ty_args
243   | Just ty_fn' <- coreView ty_fn = prDictOfTyApp ty_fn' ty_args
244 prDictOfTyApp (TyConApp tc _) ty_args
245   = do
246       dfun <- liftM Var $ maybeV (lookupTyConPR tc)
247       prDFunApply dfun ty_args
248 prDictOfTyApp _ _ = noV
249
250 prDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
251 prDFunApply dfun tys
252   = do
253       dicts <- mapM prDictOfType tys
254       return $ mkApps (mkTyApps dfun tys) dicts
255
256 wrapPR :: Type -> VM CoreExpr
257 wrapPR ty
258   = do
259       pa_dict <- paDictOfType ty
260       pr_dfun <- prDFunOfTyCon =<< builtin wrapTyCon
261       return $ mkApps pr_dfun [Type ty, pa_dict]
262
263 replicatePD :: CoreExpr -> CoreExpr -> VM CoreExpr
264 replicatePD len x = liftM (`mkApps` [len,x])
265                           (paMethod replicatePDVar "replicatePD" (exprType x))
266
267 emptyPD :: Type -> VM CoreExpr
268 emptyPD = paMethod emptyPDVar "emptyPD"
269
270 packByTagPD :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
271                  -> VM CoreExpr
272 packByTagPD ty xs len tags t
273   = liftM (`mkApps` [xs, len, tags, t])
274           (paMethod packByTagPDVar "packByTagPD" ty)
275
276 combinePD :: Type -> CoreExpr -> CoreExpr -> [CoreExpr]
277           -> VM CoreExpr
278 combinePD ty len sel xs
279   = liftM (`mkApps` (len : sel : xs))
280           (paMethod (combinePDVar n) ("combine" ++ show n ++ "PD") ty)
281   where
282     n = length xs
283
284 liftPD :: CoreExpr -> VM CoreExpr
285 liftPD x
286   = do
287       lc <- builtin liftingContext
288       replicatePD (Var lc) x
289
290 zipScalars :: [Type] -> Type -> VM CoreExpr
291 zipScalars arg_tys res_ty
292   = do
293       scalar <- builtin scalarClass
294       (dfuns, _) <- mapAndUnzipM (\ty -> lookupInst scalar [ty]) ty_args
295       zipf <- builtin (scalarZip $ length arg_tys)
296       return $ Var zipf `mkTyApps` ty_args `mkApps` map Var dfuns
297     where
298       ty_args = arg_tys ++ [res_ty]
299
300 scalarClosure :: [Type] -> Type -> CoreExpr -> CoreExpr -> VM CoreExpr
301 scalarClosure arg_tys res_ty scalar_fun array_fun
302   = do
303       ctr <- builtin (closureCtrFun $ length arg_tys)
304       pas <- mapM paDictOfType (init arg_tys)
305       return $ Var ctr `mkTyApps` (arg_tys ++ [res_ty])
306                        `mkApps`   (pas ++ [scalar_fun, array_fun])
307
308 newLocalVVar :: FastString -> Type -> VM VVar
309 newLocalVVar fs vty
310   = do
311       lty <- mkPDataType vty
312       vv  <- newLocalVar fs vty
313       lv  <- newLocalVar fs lty
314       return (vv,lv)
315
316 polyAbstract :: [TyVar] -> ([Var] -> VM a) -> VM a
317 polyAbstract tvs p
318   = localV
319   $ do
320       mdicts <- mapM mk_dict_var tvs
321       zipWithM_ (\tv -> maybe (defLocalTyVar tv)
322                               (defLocalTyVarWithPA tv . Var)) tvs mdicts
323       p (mk_args mdicts)
324   where
325     mk_dict_var tv = do
326                        r <- paDictArgType tv
327                        case r of
328                          Just ty -> liftM Just (newLocalVar (fsLit "dPA") ty)
329                          Nothing -> return Nothing
330
331     mk_args mdicts = [dict | Just dict <- mdicts]
332
333 polyArity :: [TyVar] -> VM Int
334 polyArity tvs = do
335                   tys <- mapM paDictArgType tvs
336                   return $ length [() | Just _ <- tys]
337
338 polyApply :: CoreExpr -> [Type] -> VM CoreExpr
339 polyApply expr tys
340   = do
341       dicts <- mapM paDictOfType tys
342       return $ expr `mkTyApps` tys `mkApps` dicts
343
344 polyVApply :: VExpr -> [Type] -> VM VExpr
345 polyVApply expr tys
346   = do
347       dicts <- mapM paDictOfType tys
348       return $ mapVect (\e -> e `mkTyApps` tys `mkApps` dicts) expr
349
350
351 data Inline = Inline Int -- arity
352             | DontInline
353
354 addInlineArity :: Inline -> Int -> Inline
355 addInlineArity (Inline m) n = Inline (m+n)
356 addInlineArity DontInline _ = DontInline
357
358 inlineMe :: Inline
359 inlineMe = Inline 0
360
361 hoistBinding :: Var -> CoreExpr -> VM ()
362 hoistBinding v e = updGEnv $ \env ->
363   env { global_bindings = (v,e) : global_bindings env }
364
365 hoistExpr :: FastString -> CoreExpr -> Inline -> VM Var
366 hoistExpr fs expr inl
367   = do
368       var <- mk_inline `liftM` newLocalVar fs (exprType expr)
369       hoistBinding var expr
370       return var
371   where
372     mk_inline var = case inl of
373                       Inline arity -> var `setIdUnfolding`
374                                       mkInlineRule needSaturated expr arity
375                       DontInline   -> var
376
377 hoistVExpr :: VExpr -> Inline -> VM VVar
378 hoistVExpr (ve, le) inl
379   = do
380       fs <- getBindName
381       vv <- hoistExpr ('v' `consFS` fs) ve inl
382       lv <- hoistExpr ('l' `consFS` fs) le (addInlineArity inl 1)
383       return (vv, lv)
384
385 hoistPolyVExpr :: [TyVar] -> Inline -> VM VExpr -> VM VExpr
386 hoistPolyVExpr tvs inline p
387   = do
388       inline' <- liftM (addInlineArity inline) (polyArity tvs)
389       expr <- closedV . polyAbstract tvs $ \args ->
390               liftM (mapVect (mkLams $ tvs ++ args)) p
391       fn   <- hoistVExpr expr inline'
392       polyVApply (vVar fn) (mkTyVarTys tvs)
393
394 takeHoisted :: VM [(Var, CoreExpr)]
395 takeHoisted
396   = do
397       env <- readGEnv id
398       setGEnv $ env { global_bindings = [] }
399       return $ global_bindings env
400
401 {-
402 boxExpr :: Type -> VExpr -> VM VExpr
403 boxExpr ty (vexpr, lexpr)
404   | Just (tycon, []) <- splitTyConApp_maybe ty
405   , isUnLiftedTyCon tycon
406   = do
407       r <- lookupBoxedTyCon tycon
408       case r of
409         Just tycon' -> let [dc] = tyConDataCons tycon'
410                        in
411                        return (mkConApp dc [vexpr], lexpr)
412         Nothing     -> return (vexpr, lexpr)
413 -}
414
415 mkClosure :: Type -> Type -> Type -> VExpr -> VExpr -> VM VExpr
416 mkClosure arg_ty res_ty env_ty (vfn,lfn) (venv,lenv)
417   = do
418       dict <- paDictOfType env_ty
419       mkv  <- builtin closureVar
420       mkl  <- builtin liftedClosureVar
421       return (Var mkv `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, venv],
422               Var mkl `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, lenv])
423
424 mkClosureApp :: Type -> Type -> VExpr -> VExpr -> VM VExpr
425 mkClosureApp arg_ty res_ty (vclo, lclo) (varg, larg)
426   = do
427       vapply <- builtin applyVar
428       lapply <- builtin liftedApplyVar
429       lc     <- builtin liftingContext
430       return (Var vapply `mkTyApps` [arg_ty, res_ty] `mkApps` [vclo, varg],
431               Var lapply `mkTyApps` [arg_ty, res_ty] `mkApps` [Var lc, lclo, larg])
432
433 buildClosures :: [TyVar] -> [VVar] -> [Type] -> Type -> VM VExpr -> VM VExpr
434 buildClosures _   _    [] _ mk_body
435   = mk_body
436 buildClosures tvs vars [arg_ty] res_ty mk_body
437   = -- liftM vInlineMe $
438       buildClosure tvs vars arg_ty res_ty mk_body
439 buildClosures tvs vars (arg_ty : arg_tys) res_ty mk_body
440   = do
441       res_ty' <- mkClosureTypes arg_tys res_ty
442       arg <- newLocalVVar (fsLit "x") arg_ty
443       -- liftM vInlineMe
444       buildClosure tvs vars arg_ty res_ty'
445         . hoistPolyVExpr tvs (Inline (length vars + 1))
446         $ do
447             lc <- builtin liftingContext
448             clo <- buildClosures tvs (vars ++ [arg]) arg_tys res_ty mk_body
449             return $ vLams lc (vars ++ [arg]) clo
450
451 -- (clo <x1,...,xn> <f,f^>, aclo (Arr lc xs1 ... xsn) <f,f^>)
452 --   where
453 --     f  = \env v -> case env of <x1,...,xn> -> e x1 ... xn v
454 --     f^ = \env v -> case env of Arr l xs1 ... xsn -> e^ l x1 ... xn v
455 --
456 buildClosure :: [TyVar] -> [VVar] -> Type -> Type -> VM VExpr -> VM VExpr
457 buildClosure tvs vars arg_ty res_ty mk_body
458   = do
459       (env_ty, env, bind) <- buildEnv vars
460       env_bndr <- newLocalVVar (fsLit "env") env_ty
461       arg_bndr <- newLocalVVar (fsLit "arg") arg_ty
462
463       fn <- hoistPolyVExpr tvs (Inline 2)
464           $ do
465               lc    <- builtin liftingContext
466               body  <- mk_body
467               return -- . vInlineMe
468                      . vLams lc [env_bndr, arg_bndr]
469                      $ bind (vVar env_bndr)
470                             (vVarApps lc body (vars ++ [arg_bndr]))
471
472       mkClosure arg_ty res_ty env_ty fn env
473
474 buildEnv :: [VVar] -> VM (Type, VExpr, VExpr -> VExpr -> VExpr)
475 buildEnv [] = do
476              ty    <- voidType
477              void  <- builtin voidVar
478              pvoid <- builtin pvoidVar
479              return (ty, vVar (void, pvoid), \_ body -> body)
480
481 buildEnv [v] = return (vVarType v, vVar v,
482                     \env body -> vLet (vNonRec v env) body)
483
484 buildEnv vs
485   = do
486       
487       (lenv_tc, lenv_tyargs) <- pdataReprTyCon ty
488
489       let venv_con   = tupleCon Boxed (length vs) 
490           [lenv_con] = tyConDataCons lenv_tc
491
492           venv       = mkCoreTup (map Var vvs)
493           lenv       = Var (dataConWrapId lenv_con)
494                        `mkTyApps` lenv_tyargs
495                        `mkApps`   map Var lvs
496
497           vbind env body = mkWildCase env ty (exprType body)
498                            [(DataAlt venv_con, vvs, body)]
499
500           lbind env body =
501             let scrut = unwrapFamInstScrut lenv_tc lenv_tyargs env
502             in
503             mkWildCase scrut (exprType scrut) (exprType body)
504               [(DataAlt lenv_con, lvs, body)]
505
506           bind (venv, lenv) (vbody, lbody) = (vbind venv vbody,
507                                               lbind lenv lbody)
508
509       return (ty, (venv, lenv), bind)
510   where
511     (vvs, lvs) = unzip vs
512     tys        = map vVarType vs
513     ty         = mkBoxedTupleTy tys
514