Use functions from BuildTyCl for vectorisation
[ghc-hetmet.git] / compiler / vectorise / VectType.hs
1 module VectType ( vectTyCon, vectType, vectTypeEnv,
2                    PAInstance, buildPADict )
3 where
4
5 #include "HsVersions.h"
6
7 import VectMonad
8 import VectUtils
9 import VectCore
10
11 import HscTypes          ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
12 import CoreSyn
13 import CoreUtils
14 import BuildTyCl
15 import DataCon
16 import TyCon
17 import Type
18 import TypeRep
19 import Coercion
20 import FamInstEnv        ( FamInst, mkLocalFamInst )
21 import InstEnv           ( Instance, mkLocalInstance, instanceDFunId )
22 import OccName
23 import MkId
24 import BasicTypes        ( StrictnessMark(..), OverlapFlag(..), boolToRecFlag )
25 import Var               ( Var )
26 import Id                ( mkWildId )
27 import Name              ( Name, getOccName )
28 import NameEnv
29 import TysWiredIn        ( intTy, intDataCon )
30 import TysPrim           ( intPrimTy )
31
32 import Unique
33 import UniqFM
34 import UniqSet
35 import Digraph           ( SCC(..), stronglyConnComp )
36
37 import Outputable
38
39 import Control.Monad  ( liftM, liftM2, zipWithM, zipWithM_ )
40 import Data.List      ( inits, tails, zipWith4 )
41
42 -- ----------------------------------------------------------------------------
43 -- Types
44
45 vectTyCon :: TyCon -> VM TyCon
46 vectTyCon tc
47   | isFunTyCon tc        = builtin closureTyCon
48   | isBoxedTupleTyCon tc = return tc
49   | isUnLiftedTyCon tc   = return tc
50   | otherwise = do
51                   r <- lookupTyCon tc
52                   case r of
53                     Just tc' -> return tc'
54
55                     -- FIXME: just for now
56                     Nothing  -> pprTrace "ccTyCon:" (ppr tc) $ return tc
57
58 vectType :: Type -> VM Type
59 vectType ty | Just ty' <- coreView ty = vectType ty'
60 vectType (TyVarTy tv) = return $ TyVarTy tv
61 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
62 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
63 vectType (FunTy ty1 ty2)   = liftM2 TyConApp (builtin closureTyCon)
64                                              (mapM vectType [ty1,ty2])
65 vectType ty@(ForAllTy _ _)
66   = do
67       mdicts   <- mapM paDictArgType tyvars
68       mono_ty' <- vectType mono_ty
69       return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
70   where
71     (tyvars, mono_ty) = splitForAllTys ty
72
73 vectType ty = pprPanic "vectType:" (ppr ty)
74
75 -- ----------------------------------------------------------------------------
76 -- Type definitions
77
78 type TyConGroup = ([TyCon], UniqSet TyCon)
79
80 data PAInstance = PAInstance {
81                     painstDFun      :: Var
82                   , painstOrigTyCon :: TyCon
83                   , painstVectTyCon :: TyCon
84                   , painstArrTyCon  :: TyCon
85                   }
86
87 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [(Var, CoreExpr)])
88 vectTypeEnv env
89   = do
90       cs <- readGEnv $ mk_map . global_tycons
91       let (conv_tcs, keep_tcs) = classifyTyCons cs groups
92           keep_dcs             = concatMap tyConDataCons keep_tcs
93       zipWithM_ defTyCon   keep_tcs keep_tcs
94       zipWithM_ defDataCon keep_dcs keep_dcs
95       new_tcs <- vectTyConDecls conv_tcs
96
97       let orig_tcs = keep_tcs ++ conv_tcs
98           vect_tcs  = keep_tcs ++ new_tcs
99
100       parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
101       dfuns    <- mapM mkPADFun vect_tcs
102       defTyConPAs (zip vect_tcs dfuns)
103       binds    <- sequence (zipWith4 buildTyConBindings orig_tcs vect_tcs parr_tcs dfuns)
104       
105       let all_new_tcs = new_tcs ++ parr_tcs
106
107       let new_env = extendTypeEnvList env
108                        (map ATyCon all_new_tcs
109                         ++ [ADataCon dc | tc <- all_new_tcs
110                                         , dc <- tyConDataCons tc])
111
112       return (new_env, map mkLocalFamInst parr_tcs, concat binds)
113   where
114     tycons = typeEnvTyCons env
115     groups = tyConGroups tycons
116
117     mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
118
119     keep_tc tc = let dcs = tyConDataCons tc
120                  in
121                  defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
122
123
124 vectTyConDecls :: [TyCon] -> VM [TyCon]
125 vectTyConDecls tcs = fixV $ \tcs' ->
126   do
127     mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
128     mapM vectTyConDecl tcs
129   where
130     lazy_zip [] _ = []
131     lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
132
133 vectTyConDecl :: TyCon -> VM TyCon
134 vectTyConDecl tc
135   = do
136       name' <- cloneName mkVectTyConOcc name
137       rhs'  <- vectAlgTyConRhs (algTyConRhs tc)
138
139       liftDs $ buildAlgTyCon name'
140                              tyvars
141                              []           -- no stupid theta
142                              rhs'
143                              rec_flag     -- FIXME: is this ok?
144                              False        -- FIXME: no generics
145                              False        -- not GADT syntax
146                              Nothing      -- not a family instance
147   where
148     name   = tyConName tc
149     tyvars = tyConTyVars tc
150     rec_flag = boolToRecFlag (isRecursiveTyCon tc)
151
152 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
153 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
154                            , is_enum   = is_enum
155                            })
156   = do
157       data_cons' <- mapM vectDataCon data_cons
158       zipWithM_ defDataCon data_cons data_cons'
159       return $ DataTyCon { data_cons = data_cons'
160                          , is_enum   = is_enum
161                          }
162
163 vectDataCon :: DataCon -> VM DataCon
164 vectDataCon dc
165   | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
166   | not . null $ dataConEqSpec   dc = pprPanic "vectDataCon: eq spec" (ppr dc)
167   | otherwise
168   = do
169       name'    <- cloneName mkVectDataConOcc name
170       tycon'   <- vectTyCon tycon
171       arg_tys  <- mapM vectType rep_arg_tys
172
173       liftDs $ buildDataCon name'
174                             False           -- not infix
175                             (map (const NotMarkedStrict) arg_tys)
176                             []              -- no labelled fields
177                             univ_tvs
178                             []              -- no existential tvs for now
179                             []              -- no eq spec for now
180                             []              -- no context
181                             arg_tys
182                             tycon'
183   where
184     name        = dataConName dc
185     univ_tvs    = dataConUnivTyVars dc
186     rep_arg_tys = dataConRepArgTys dc
187     tycon       = dataConTyCon dc
188
189 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
190 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
191   do
192     name'  <- cloneName mkPArrayTyConOcc orig_name
193     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
194     parray <- builtin parrayTyCon
195
196     liftDs $ buildAlgTyCon name'
197                            tyvars
198                            []          -- no stupid theta
199                            rhs
200                            rec_flag    -- FIXME: is this ok?
201                            False       -- FIXME: no generics
202                            False       -- not GADT syntax
203                            (Just (parray, [mkTyConApp vect_tc (map mkTyVarTy tyvars)]))
204   where
205     orig_name = tyConName orig_tc
206     tyvars = tyConTyVars vect_tc
207     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
208     
209
210 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
211 buildPArrayTyConRhs orig_name vect_tc repr_tc
212   = do
213       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
214       return $ DataTyCon { data_cons = [data_con], is_enum = False }
215
216 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
217 buildPArrayDataCon orig_name vect_tc repr_tc
218   = do
219       dc_name  <- cloneName mkPArrayDataConOcc orig_name
220       shape    <- tyConShape vect_tc
221       repr_tys <- mapM mkPArrayType types
222
223       liftDs $ buildDataCon dc_name
224                             False                  -- not infix
225                             (shapeStrictness shape ++ map (const NotMarkedStrict) repr_tys)
226                             []                     -- no field labels
227                             (tyConTyVars vect_tc)
228                             []                     -- no existentials
229                             []                     -- no eq spec
230                             []                     -- no context
231                             (shapeReprTys shape ++ repr_tys)
232                             repr_tc
233   where
234     types = [ty | dc <- tyConDataCons vect_tc
235                 , ty <- dataConRepArgTys dc]
236
237 mkPADFun :: TyCon -> VM Var
238 mkPADFun vect_tc
239   = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
240
241 data Shape = Shape {
242                shapeReprTys    :: [Type]
243              , shapeStrictness :: [StrictnessMark]
244              , shapeLength     :: [CoreExpr] -> VM CoreExpr
245              , shapeReplicate  :: CoreExpr -> CoreExpr -> VM [CoreExpr]
246              }
247
248 tyConShape :: TyCon -> VM Shape
249 tyConShape vect_tc
250   | isProductTyCon vect_tc
251   = return $ Shape {
252                 shapeReprTys    = [intPrimTy]
253               , shapeStrictness = [NotMarkedStrict]
254               , shapeLength     = \[len] -> return len
255               , shapeReplicate  = \len _ -> return [len]
256               }
257
258   | otherwise
259   = do
260       repr_ty <- mkPArrayType intTy   -- FIXME: we want to unbox this
261       return $ Shape {
262                  shapeReprTys    = [repr_ty]
263                , shapeStrictness = [MarkedStrict]
264                , shapeLength     = \[sel] -> lengthPA sel
265                , shapeReplicate  = \len n -> do
266                                                e <- replicatePA len n
267                                                return [e]
268                }
269
270 buildTyConBindings :: TyCon -> TyCon -> TyCon -> Var -> VM [(Var, CoreExpr)]
271 buildTyConBindings orig_tc vect_tc arr_tc dfun
272   = do
273       shape <- tyConShape vect_tc
274       sequence_ (zipWith4 (vectDataConWorker shape vect_tc arr_tc arr_dc)
275                           orig_dcs
276                           vect_dcs
277                           (inits repr_tys)
278                           (tails repr_tys))
279       dict <- buildPADict shape vect_tc arr_tc dfun
280       binds <- takeHoisted
281       return $ (dfun, dict) : binds
282   where
283     orig_dcs = tyConDataCons orig_tc
284     vect_dcs = tyConDataCons vect_tc
285     [arr_dc] = tyConDataCons arr_tc
286
287     repr_tys = map dataConRepArgTys vect_dcs
288
289 vectDataConWorker :: Shape -> TyCon -> TyCon -> DataCon
290                   -> DataCon -> DataCon -> [[Type]] -> [[Type]]
291                   -> VM ()
292 vectDataConWorker shape vect_tc arr_tc arr_dc orig_dc vect_dc pre (dc_tys : post)
293   = do
294       clo <- closedV
295            . inBind orig_worker
296            . polyAbstract tvs $ \abstract ->
297              liftM (abstract . vectorised)
298            $ buildClosures tvs [] dc_tys res_ty (liftM2 (,) mk_vect mk_lift)
299
300       worker <- cloneId mkVectOcc orig_worker (exprType clo)
301       hoistBinding worker clo
302       defGlobalVar orig_worker worker
303       return ()
304   where
305     tvs     = tyConTyVars vect_tc
306     arg_tys = mkTyVarTys tvs
307     res_ty  = mkTyConApp vect_tc arg_tys
308
309     orig_worker = dataConWorkId orig_dc
310
311     mk_vect = return . mkConApp vect_dc $ map Type arg_tys
312     mk_lift = do
313                 len     <- newLocalVar FSLIT("n") intPrimTy
314                 arr_tys <- mapM mkPArrayType dc_tys
315                 args    <- mapM (newLocalVar FSLIT("xs")) arr_tys
316                 shapes  <- shapeReplicate shape
317                                           (Var len)
318                                           (mkDataConTag vect_dc)
319                 
320                 empty_pre  <- mapM emptyPA (concat pre)
321                 empty_post <- mapM emptyPA (concat post)
322
323                 return . mkLams (len : args)
324                        . wrapFamInstBody arr_tc arg_tys
325                        . mkConApp arr_dc
326                        $ map Type arg_tys ++ shapes
327                                           ++ empty_pre
328                                           ++ map Var args
329                                           ++ empty_post
330
331 buildPADict :: Shape -> TyCon -> TyCon -> Var -> VM CoreExpr
332 buildPADict shape vect_tc arr_tc dfun
333   = polyAbstract tvs $ \abstract ->
334     do
335       meth_binds <- mapM (mk_method shape) paMethods
336       let meth_exprs = map (Var . fst) meth_binds
337
338       pa_dc <- builtin paDataCon
339       let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
340           body = Let (Rec meth_binds) dict
341       return . mkInlineMe $ abstract body
342   where
343     tvs = tyConTyVars arr_tc
344     arg_tys = mkTyVarTys tvs
345
346     mk_method shape (name, build)
347       = localV
348       $ do
349           body <- build shape vect_tc arr_tc
350           var  <- newLocalVar name (exprType body)
351           return (var, mkInlineMe body)
352           
353 paMethods = [(FSLIT("lengthPA"),    buildLengthPA),
354              (FSLIT("replicatePA"), buildReplicatePA)]
355
356 buildLengthPA :: Shape -> TyCon -> TyCon -> VM CoreExpr
357 buildLengthPA shape vect_tc arr_tc
358   = do
359       parr_ty <- mkPArrayType (mkTyConApp vect_tc arg_tys)
360       arg    <- newLocalVar FSLIT("xs") parr_ty
361       shapes <- mapM (newLocalVar FSLIT("sh")) shape_tys
362       wilds  <- mapM newDummyVar repr_tys
363       let scrut    = unwrapFamInstScrut arr_tc arg_tys (Var arg)
364           scrut_ty = exprType scrut
365
366       body <- shapeLength shape (map Var shapes)
367
368       return . Lam arg
369              $ Case scrut (mkWildId scrut_ty) intPrimTy
370                     [(DataAlt repr_dc, shapes ++ wilds, body)]
371   where
372     arg_tys = mkTyVarTys $ tyConTyVars arr_tc
373     [repr_dc] = tyConDataCons arr_tc
374     
375     shape_tys = shapeReprTys shape
376     repr_tys  = drop (length shape_tys) (dataConRepArgTys repr_dc)
377
378 -- data T = C0 t1 ... tm
379 --          ...
380 --          Ck u1 ... un
381 --
382 -- data [:T:] = A ![:Int:] [:t1:] ... [:un:]
383 --
384 -- replicatePA :: Int# -> T -> [:T:]
385 -- replicatePA n# t
386 --   = let c = case t of
387 --               C0 _ ... _ -> 0
388 --               ...
389 --               Ck _ ... _ -> k
390 --
391 --         xs1 = case t of
392 --                 C0 x1 _ ... _ -> replicatePA @t1 n# x1
393 --                 _             -> emptyPA @t1
394 --
395 --         ...
396 --
397 --         ysn = case t of
398 --                 Ck _ ... _ yn -> replicatePA @un n# yn
399 --                 _             -> emptyPA @un
400 --     in
401 --     A (replicatePA @Int n# c) xs1 ... ysn
402 --
403 --
404
405 buildReplicatePA :: Shape -> TyCon -> TyCon -> VM CoreExpr
406 buildReplicatePA shape vect_tc arr_tc
407   = do
408       len_var <- newLocalVar FSLIT("n") intPrimTy
409       val_var <- newLocalVar FSLIT("x") val_ty
410
411       let len = Var len_var
412           val = Var val_var
413
414       shape_reprs <- shapeReplicate shape len (ctr_num val)
415       reprs <- liftM concat $ mapM (mk_comp_arrs len val) vect_dcs
416
417       return . mkLams [len_var, val_var]
418              . wrapFamInstBody arr_tc arg_tys
419              $ mkConApp arr_dc (map Type arg_tys ++ shape_reprs ++ reprs)
420   where
421     arg_tys = mkTyVarTys (tyConTyVars arr_tc)
422     val_ty  = mkTyConApp vect_tc arg_tys
423     wild    = mkWildId val_ty
424     vect_dcs = tyConDataCons vect_tc
425     [arr_dc] = tyConDataCons arr_tc
426
427     ctr_num val = Case val wild intTy (zipWith ctr_num_alt vect_dcs [0..])
428     ctr_num_alt dc i = (DataAlt dc, map mkWildId (dataConRepArgTys dc),
429                                     mkConApp intDataCon [mkIntLitInt i])
430
431
432     mk_comp_arrs len val dc = let tys = dataConRepArgTys dc
433                                   wilds = map mkWildId tys
434                               in
435                               sequence (zipWith3 (mk_comp_arr len val dc)
436                                        tys (inits wilds) (tails wilds))
437
438     mk_comp_arr len val dc ty pre (_:post)
439       = do
440           var   <- newLocalVar FSLIT("x") ty
441           rep   <- replicatePA len (Var var)
442           empty <- emptyPA ty
443           arr_ty <- mkPArrayType ty
444
445           return $ Case val wild arr_ty
446                      [(DEFAULT, [], empty), (DataAlt dc, pre ++ (var : post), rep)]
447
448 -- | Split the given tycons into two sets depending on whether they have to be
449 -- converted (first list) or not (second list). The first argument contains
450 -- information about the conversion status of external tycons:
451 -- 
452 --   * tycons which have converted versions are mapped to True
453 --   * tycons which are not changed by vectorisation are mapped to False
454 --   * tycons which can't be converted are not elements of the map
455 --
456 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
457 classifyTyCons = classify [] []
458   where
459     classify conv keep cs [] = (conv, keep)
460     classify conv keep cs ((tcs, ds) : rs)
461       | can_convert && must_convert
462         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
463       | can_convert
464         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
465       | otherwise
466         = classify conv keep cs rs
467       where
468         refs = ds `delListFromUniqSet` tcs
469
470         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
471         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
472
473         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
474     
475 -- | Compute mutually recursive groups of tycons in topological order
476 --
477 tyConGroups :: [TyCon] -> [TyConGroup]
478 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
479   where
480     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
481                                 , let ds = tyConsOfTyCon tc]
482
483     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
484     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
485       where
486         (tcs, dss) = unzip els
487
488 tyConsOfTyCon :: TyCon -> UniqSet TyCon
489 tyConsOfTyCon 
490   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
491
492 tyConsOfType :: Type -> UniqSet TyCon
493 tyConsOfType ty
494   | Just ty' <- coreView ty    = tyConsOfType ty'
495 tyConsOfType (TyVarTy v)       = emptyUniqSet
496 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
497   where
498     extend | isUnLiftedTyCon tc
499            || isTupleTyCon   tc = id
500
501            | otherwise          = (`addOneToUniqSet` tc)
502
503 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
504 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
505                                  `addOneToUniqSet` funTyCon
506 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
507 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
508
509 tyConsOfTypes :: [Type] -> UniqSet TyCon
510 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
511