Vectorisation of algebraic case expressions
[ghc-hetmet.git] / compiler / vectorise / VectType.hs
1 {-# OPTIONS -w #-}
2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
6 -- for details
7
8 module VectType ( vectTyCon, vectType, vectTypeEnv,
9                   mkRepr, arrShapeTys, arrShapeVars, arrSelector,
10                   PAInstance, buildPADict )
11 where
12
13 #include "HsVersions.h"
14
15 import VectMonad
16 import VectUtils
17 import VectCore
18
19 import HscTypes          ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
20 import CoreSyn
21 import CoreUtils
22 import BuildTyCl
23 import DataCon
24 import TyCon
25 import Type
26 import TypeRep
27 import Coercion
28 import FamInstEnv        ( FamInst, mkLocalFamInst )
29 import InstEnv           ( Instance, mkLocalInstance, instanceDFunId )
30 import OccName
31 import MkId
32 import BasicTypes        ( StrictnessMark(..), OverlapFlag(..), boolToRecFlag )
33 import Var               ( Var )
34 import Id                ( mkWildId )
35 import Name              ( Name, getOccName )
36 import NameEnv
37 import TysWiredIn
38 import TysPrim           ( intPrimTy )
39
40 import Unique
41 import UniqFM
42 import UniqSet
43 import Util              ( singleton )
44 import Digraph           ( SCC(..), stronglyConnComp )
45
46 import Outputable
47
48 import Control.Monad  ( liftM, liftM2, zipWithM, zipWithM_, mapAndUnzipM )
49 import Data.List      ( inits, tails, zipWith4, zipWith5 )
50
51 -- ----------------------------------------------------------------------------
52 -- Types
53
54 vectTyCon :: TyCon -> VM TyCon
55 vectTyCon tc
56   | isFunTyCon tc        = builtin closureTyCon
57   | isBoxedTupleTyCon tc = return tc
58   | isUnLiftedTyCon tc   = return tc
59   | otherwise = do
60                   r <- lookupTyCon tc
61                   case r of
62                     Just tc' -> return tc'
63
64                     -- FIXME: just for now
65                     Nothing  -> pprTrace "ccTyCon:" (ppr tc) $ return tc
66
67 vectType :: Type -> VM Type
68 vectType ty | Just ty' <- coreView ty = vectType ty'
69 vectType (TyVarTy tv) = return $ TyVarTy tv
70 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
71 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
72 vectType (FunTy ty1 ty2)   = liftM2 TyConApp (builtin closureTyCon)
73                                              (mapM vectType [ty1,ty2])
74 vectType ty@(ForAllTy _ _)
75   = do
76       mdicts   <- mapM paDictArgType tyvars
77       mono_ty' <- vectType mono_ty
78       return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
79   where
80     (tyvars, mono_ty) = splitForAllTys ty
81
82 vectType ty = pprPanic "vectType:" (ppr ty)
83
84 -- ----------------------------------------------------------------------------
85 -- Type definitions
86
87 type TyConGroup = ([TyCon], UniqSet TyCon)
88
89 data PAInstance = PAInstance {
90                     painstDFun      :: Var
91                   , painstOrigTyCon :: TyCon
92                   , painstVectTyCon :: TyCon
93                   , painstArrTyCon  :: TyCon
94                   }
95
96 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [(Var, CoreExpr)])
97 vectTypeEnv env
98   = do
99       cs <- readGEnv $ mk_map . global_tycons
100       let (conv_tcs, keep_tcs) = classifyTyCons cs groups
101           keep_dcs             = concatMap tyConDataCons keep_tcs
102       zipWithM_ defTyCon   keep_tcs keep_tcs
103       zipWithM_ defDataCon keep_dcs keep_dcs
104       new_tcs <- vectTyConDecls conv_tcs
105
106       let orig_tcs = keep_tcs ++ conv_tcs
107           vect_tcs  = keep_tcs ++ new_tcs
108
109       repr_tcs <- zipWithM buildPReprTyCon   orig_tcs vect_tcs
110       parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
111       dfuns    <- mapM mkPADFun vect_tcs
112       defTyConPAs (zip vect_tcs dfuns)
113       binds    <- sequence (zipWith5 buildTyConBindings orig_tcs
114                                                         vect_tcs
115                                                         repr_tcs
116                                                         parr_tcs
117                                                         dfuns)
118
119       let all_new_tcs = new_tcs ++ repr_tcs ++ parr_tcs
120
121       let new_env = extendTypeEnvList env
122                        (map ATyCon all_new_tcs
123                         ++ [ADataCon dc | tc <- all_new_tcs
124                                         , dc <- tyConDataCons tc])
125
126       return (new_env, map mkLocalFamInst (repr_tcs ++ parr_tcs), concat binds)
127   where
128     tycons = typeEnvTyCons env
129     groups = tyConGroups tycons
130
131     mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
132
133     keep_tc tc = let dcs = tyConDataCons tc
134                  in
135                  defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
136
137
138 vectTyConDecls :: [TyCon] -> VM [TyCon]
139 vectTyConDecls tcs = fixV $ \tcs' ->
140   do
141     mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
142     mapM vectTyConDecl tcs
143   where
144     lazy_zip [] _ = []
145     lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
146
147 vectTyConDecl :: TyCon -> VM TyCon
148 vectTyConDecl tc
149   = do
150       name' <- cloneName mkVectTyConOcc name
151       rhs'  <- vectAlgTyConRhs (algTyConRhs tc)
152
153       liftDs $ buildAlgTyCon name'
154                              tyvars
155                              []           -- no stupid theta
156                              rhs'
157                              rec_flag     -- FIXME: is this ok?
158                              False        -- FIXME: no generics
159                              False        -- not GADT syntax
160                              Nothing      -- not a family instance
161   where
162     name   = tyConName tc
163     tyvars = tyConTyVars tc
164     rec_flag = boolToRecFlag (isRecursiveTyCon tc)
165
166 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
167 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
168                            , is_enum   = is_enum
169                            })
170   = do
171       data_cons' <- mapM vectDataCon data_cons
172       zipWithM_ defDataCon data_cons data_cons'
173       return $ DataTyCon { data_cons = data_cons'
174                          , is_enum   = is_enum
175                          }
176
177 vectDataCon :: DataCon -> VM DataCon
178 vectDataCon dc
179   | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
180   | not . null $ dataConEqSpec   dc = pprPanic "vectDataCon: eq spec" (ppr dc)
181   | otherwise
182   = do
183       name'    <- cloneName mkVectDataConOcc name
184       tycon'   <- vectTyCon tycon
185       arg_tys  <- mapM vectType rep_arg_tys
186
187       liftDs $ buildDataCon name'
188                             False           -- not infix
189                             (map (const NotMarkedStrict) arg_tys)
190                             []              -- no labelled fields
191                             univ_tvs
192                             []              -- no existential tvs for now
193                             []              -- no eq spec for now
194                             []              -- no context
195                             arg_tys
196                             tycon'
197   where
198     name        = dataConName dc
199     univ_tvs    = dataConUnivTyVars dc
200     rep_arg_tys = dataConRepArgTys dc
201     tycon       = dataConTyCon dc
202
203 mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
204 mk_fam_inst fam_tc arg_tc
205   = (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
206
207 buildPReprTyCon :: TyCon -> TyCon -> VM TyCon
208 buildPReprTyCon orig_tc vect_tc
209   = do
210       name     <- cloneName mkPReprTyConOcc (tyConName orig_tc)
211       rhs_ty   <- buildPReprType vect_tc
212       prepr_tc <- builtin preprTyCon
213       liftDs $ buildSynTyCon name
214                              tyvars
215                              (SynonymTyCon rhs_ty)
216                              (Just $ mk_fam_inst prepr_tc vect_tc)
217   where
218     tyvars = tyConTyVars vect_tc
219
220
221 data Repr = ProdRepr {
222               prod_components   :: [Type]
223             , prod_tycon        :: TyCon
224             , prod_data_con     :: DataCon
225             , prod_arr_tycon    :: TyCon
226             , prod_arr_data_con :: DataCon
227             }
228
229           | SumRepr {
230               sum_components    :: [Repr]
231             , sum_tycon         :: TyCon
232             , sum_arr_tycon     :: TyCon
233             , sum_arr_data_con  :: DataCon
234             }
235
236           | IdRepr Type
237
238           | VoidRepr {
239               void_tycon        :: TyCon
240             , void_bottom       :: CoreExpr
241             }
242
243           | EnumRepr {
244               enum_tycon        :: TyCon
245             , enum_data_con     :: DataCon
246             , enum_arr_tycon    :: TyCon
247             , enum_arr_data_con :: DataCon
248             }
249
250 voidRepr :: VM Repr
251 voidRepr
252   = do
253       tycon <- builtin voidTyCon
254       var   <- builtin voidVar
255       return $ VoidRepr {
256                  void_tycon  = tycon
257                , void_bottom = Var var
258                }
259
260 enumRepr :: VM Repr
261 enumRepr
262   = do
263       (arr_tycon, _) <- parrayReprTyCon intTy
264       let [arr_data_con] = tyConDataCons arr_tycon
265
266       return $ EnumRepr {
267                  enum_tycon       = tycon
268                , enum_data_con     = data_con
269                , enum_arr_tycon    = arr_tycon
270                , enum_arr_data_con = arr_data_con
271                }
272   where
273     tycon = intTyCon
274     data_con = intDataCon
275
276 unboxedProductRepr :: [Type] -> VM Repr
277 unboxedProductRepr []   = voidRepr
278 unboxedProductRepr [ty] = return $ IdRepr ty
279 unboxedProductRepr tys  = boxedProductRepr tys
280
281 boxedProductRepr :: [Type] -> VM Repr
282 boxedProductRepr tys
283   = do
284       tycon <- builtin (prodTyCon arity)
285       let [data_con] = tyConDataCons tycon
286
287       (arr_tycon, _) <- parrayReprTyCon $ mkTyConApp tycon tys
288       let [arr_data_con] = tyConDataCons arr_tycon
289
290       return $ ProdRepr {
291                  prod_components   = tys
292                , prod_tycon        = tycon
293                , prod_data_con     = data_con
294                , prod_arr_tycon    = arr_tycon
295                , prod_arr_data_con = arr_data_con
296                }
297   where
298     arity = length tys
299
300 sumRepr :: [Repr] -> VM Repr
301 sumRepr []     = voidRepr
302 sumRepr [repr] = boxRepr repr
303 sumRepr reprs
304   = do
305       tycon <- builtin (sumTyCon arity)
306       (arr_tycon, _) <- parrayReprTyCon
307                       . mkTyConApp tycon
308                       $ map reprType reprs
309
310       let [arr_data_con] = tyConDataCons arr_tycon
311
312       return $ SumRepr {
313                  sum_components   = reprs
314                , sum_tycon        = tycon
315                , sum_arr_tycon    = arr_tycon
316                , sum_arr_data_con = arr_data_con
317                }
318   where
319     arity = length reprs
320
321 splitSumRepr :: Repr -> [Repr]
322 splitSumRepr (SumRepr { sum_components = reprs }) = reprs
323 splitSumRepr repr                                 = [repr]
324
325 boxRepr :: Repr -> VM Repr
326 boxRepr (VoidRepr {}) = boxedProductRepr []
327 boxRepr (IdRepr ty)   = boxedProductRepr [ty]
328 boxRepr repr          = return repr
329
330 reprType :: Repr -> Type
331 reprType (ProdRepr { prod_tycon = tycon, prod_components = tys })
332   = mkTyConApp tycon tys
333 reprType (SumRepr { sum_tycon = tycon, sum_components = reprs })
334   = mkTyConApp tycon (map reprType reprs)
335 reprType (IdRepr ty) = ty
336 reprType (VoidRepr { void_tycon = tycon }) = mkTyConApp tycon []
337 reprType (EnumRepr { enum_tycon = tycon }) = mkTyConApp tycon []
338
339 arrReprType :: Repr -> VM Type
340 arrReprType = mkPArrayType . reprType
341
342 arrShapeTys :: Repr -> VM [Type]
343 arrShapeTys (SumRepr  {})
344   = do
345       int_arr <- builtin parrayIntPrimTyCon
346       return [intPrimTy, mkTyConApp int_arr [], mkTyConApp int_arr []]
347 arrShapeTys (ProdRepr {}) = return [intPrimTy]
348 arrShapeTys (IdRepr _)    = return []
349 arrShapeTys (VoidRepr {}) = return [intPrimTy]
350 arrShapeTys (EnumRepr {}) = return [intPrimTy]
351
352 arrShapeVars :: Repr -> VM [Var]
353 arrShapeVars repr = mapM (newLocalVar FSLIT("sh")) =<< arrShapeTys repr
354
355 replicateShape :: Repr -> CoreExpr -> CoreExpr -> VM [CoreExpr]
356 replicateShape (ProdRepr {}) len _ = return [len]
357 replicateShape (SumRepr {})  len tag
358   = do
359       rep <- builtin replicatePAIntPrimVar
360       up  <- builtin upToPAIntPrimVar
361       return [len, Var rep `mkApps` [len, tag], Var up `App` len]
362 replicateShape (IdRepr _) _ _ = return []
363 replicateShape (VoidRepr {}) len _ = return [len]
364 replicateShape (EnumRepr {}) len _ = return [len]
365
366 arrSelector :: Repr -> [CoreExpr] -> VM (CoreExpr, CoreExpr, CoreExpr)
367 arrSelector (SumRepr {}) [len, sel, is] = return (len, sel, is)
368
369 emptyArrRepr :: Repr -> VM [CoreExpr]
370 emptyArrRepr (SumRepr { sum_components = prods })
371   = liftM concat $ mapM emptyArrRepr prods
372 emptyArrRepr (ProdRepr { prod_components = [] })
373   = return [Var unitDataConId]
374 emptyArrRepr (ProdRepr { prod_components = tys })
375   = mapM emptyPA tys
376 emptyArrRepr (IdRepr ty)
377   = liftM singleton $ emptyPA ty
378 emptyArrRepr (VoidRepr { void_tycon = tycon })
379   = liftM singleton $ emptyPA (mkTyConApp tycon [])
380 emptyArrRepr (EnumRepr { enum_tycon = tycon })
381   = liftM singleton $ emptyPA (mkTyConApp tycon [])
382
383 arrReprTys :: Repr -> VM [Type]
384 arrReprTys (SumRepr { sum_components = reprs })
385   = liftM concat $ mapM arrReprTys reprs
386 arrReprTys (ProdRepr { prod_components = [] })
387   = return [unitTy]
388 arrReprTys (ProdRepr { prod_components = tys })
389   = mapM mkPArrayType tys
390 arrReprTys (IdRepr ty)
391   = liftM singleton $ mkPArrayType ty
392 arrReprTys (VoidRepr { void_tycon = tycon })
393   = liftM singleton $ mkPArrayType (mkTyConApp tycon [])
394 arrReprTys (EnumRepr {})
395   = liftM singleton $ mkPArrayType intPrimTy
396
397 arrReprTys' :: Repr -> VM [[Type]]
398 arrReprTys' (SumRepr { sum_components = reprs })
399   = mapM arrReprTys reprs
400 arrReprTys' repr = liftM singleton $ arrReprTys repr
401
402 arrReprVars :: Repr -> VM [[Var]]
403 arrReprVars repr
404   = mapM (mapM (newLocalVar FSLIT("rs"))) =<< arrReprTys' repr
405
406 mkRepr :: TyCon -> VM Repr
407 mkRepr vect_tc
408   | [tys] <- rep_tys = boxedProductRepr tys
409   | all null rep_tys = enumRepr
410   | otherwise        = sumRepr =<< mapM unboxedProductRepr rep_tys
411   where
412     rep_tys = map dataConRepArgTys $ tyConDataCons vect_tc
413
414 buildPReprType :: TyCon -> VM Type
415 buildPReprType = liftM reprType . mkRepr
416
417 buildToPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
418 buildToPRepr repr vect_tc prepr_tc _
419   = do
420       arg    <- newLocalVar FSLIT("x") arg_ty
421       result <- to_repr repr (Var arg)
422
423       return . Lam arg
424              . wrapFamInstBody prepr_tc var_tys
425              $ result
426   where
427     var_tys = mkTyVarTys $ tyConTyVars vect_tc
428     arg_ty  = mkTyConApp vect_tc var_tys
429     res_ty  = reprType repr
430
431     cons    = tyConDataCons vect_tc
432     [con]   = cons
433
434     to_repr (SumRepr { sum_components = prods
435                      , sum_tycon      = tycon })
436             expr
437       = do
438           (vars, bodies) <- mapAndUnzipM to_unboxed prods
439           return . Case expr (mkWildId (exprType expr)) res_ty
440                  $ zipWith4 mk_alt cons vars (tyConDataCons tycon) bodies
441       where
442         mk_alt con vars sum_con body
443           = (DataAlt con, vars, mkConApp sum_con (ty_args ++ [body]))
444
445         ty_args = map (Type . reprType) prods
446
447     to_repr (EnumRepr { enum_data_con = data_con }) expr
448       = return . Case expr (mkWildId (exprType expr)) res_ty
449                $ map mk_alt cons
450       where
451         mk_alt con = (DataAlt con, [], mkConApp data_con [mkDataConTag con])
452
453     to_repr prod expr
454       = do
455           (vars, body) <- to_unboxed prod
456           return $ Case expr (mkWildId (exprType expr)) res_ty
457                    [(DataAlt con, vars, body)]
458
459     to_unboxed (ProdRepr { prod_components = tys
460                          , prod_data_con   = data_con })
461       = do
462           vars <- mapM (newLocalVar FSLIT("r")) tys
463           return (vars, mkConApp data_con (map Type tys ++ map Var vars))
464
465     to_unboxed (IdRepr ty)
466       = do
467           var <- newLocalVar FSLIT("y") ty
468           return ([var], Var var)
469
470     to_unboxed (VoidRepr { void_bottom = bottom })
471       = return ([], bottom)
472
473
474 buildFromPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
475 buildFromPRepr repr vect_tc prepr_tc _
476   = do
477       arg_ty <- mkPReprType res_ty
478       arg    <- newLocalVar FSLIT("x") arg_ty
479
480       liftM (Lam arg)
481            . from_repr repr
482            $ unwrapFamInstScrut prepr_tc var_tys (Var arg)
483   where
484     var_tys = mkTyVarTys $ tyConTyVars vect_tc
485     res_ty  = mkTyConApp vect_tc var_tys
486
487     cons    = map (`mkConApp` map Type var_tys) (tyConDataCons vect_tc)
488     [con]   = cons
489
490     from_repr repr@(SumRepr { sum_components = prods
491                             , sum_tycon      = tycon })
492               expr
493       = do
494           vars   <- mapM (newLocalVar FSLIT("x")) (map reprType prods)
495           bodies <- sequence . zipWith3 from_unboxed prods cons
496                              $ map Var vars
497           return . Case expr (mkWildId (reprType repr)) res_ty
498                  $ zipWith3 sum_alt (tyConDataCons tycon) vars bodies
499       where
500         sum_alt data_con var body = (DataAlt data_con, [var], body)
501
502     from_repr repr@(EnumRepr { enum_data_con = data_con }) expr
503       = do
504           var <- newLocalVar FSLIT("n") intPrimTy
505
506           let res = Case (Var var) (mkWildId intPrimTy) res_ty
507                   $ (DEFAULT, [], error_expr)
508                   : zipWith mk_alt (tyConDataCons vect_tc) cons
509
510           return $ Case expr (mkWildId (reprType repr)) res_ty
511                    [(DataAlt data_con, [var], res)]
512       where
513         mk_alt data_con con = (LitAlt (mkDataConTagLit data_con), [], con)
514
515         error_expr = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty
516                    . showSDoc
517                    $ sep [text "Invalid NDP representation of", ppr vect_tc]
518
519     from_repr repr expr = from_unboxed repr con expr
520
521     from_unboxed prod@(ProdRepr { prod_components = tys
522                                 , prod_data_con   = data_con })
523               con
524               expr
525       = do
526           vars <- mapM (newLocalVar FSLIT("y")) tys
527           return $ Case expr (mkWildId (reprType prod)) res_ty
528                    [(DataAlt data_con, vars, con `mkVarApps` vars)]
529
530     from_unboxed (IdRepr _) con expr
531        = return $ con `App` expr
532
533     from_unboxed (VoidRepr {}) con expr
534        = return con
535
536 buildToArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
537 buildToArrPRepr repr vect_tc prepr_tc arr_tc
538   = do
539       arg_ty     <- mkPArrayType el_ty
540       arg        <- newLocalVar FSLIT("xs") arg_ty
541
542       res_ty     <- mkPArrayType (reprType repr)
543
544       shape_vars <- arrShapeVars repr
545       repr_vars  <- arrReprVars  repr
546
547       parray_co  <- mkBuiltinCo parrayTyCon
548
549       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
550           co           = mkAppCoercion parray_co
551                        . mkSymCoercion
552                        $ mkTyConApp repr_co var_tys
553
554           scrut   = unwrapFamInstScrut arr_tc var_tys (Var arg)
555
556       result <- to_repr shape_vars repr_vars repr
557
558       return . Lam arg
559              . mkCoerce co
560              $ Case scrut (mkWildId (mkTyConApp arr_tc var_tys)) res_ty
561                [(DataAlt arr_dc, shape_vars ++ concat repr_vars, result)]
562   where
563     var_tys = mkTyVarTys $ tyConTyVars vect_tc
564     el_ty   = mkTyConApp vect_tc var_tys
565
566     [arr_dc] = tyConDataCons arr_tc
567
568     to_repr shape_vars@(len_var : _)
569             repr_vars
570             (SumRepr { sum_components   = prods
571                      , sum_arr_tycon    = tycon
572                      , sum_arr_data_con = data_con })
573       = do
574           exprs <- zipWithM to_prod repr_vars prods
575
576           return . wrapFamInstBody tycon tys
577                  . mkConApp data_con
578                  $ map Type tys ++ map Var shape_vars ++ exprs
579       where
580         tys = map reprType prods
581
582     to_repr [len_var]
583             [repr_vars]
584             (ProdRepr { prod_components   = tys
585                       , prod_arr_tycon    = tycon
586                       , prod_arr_data_con = data_con })
587        = return . wrapFamInstBody tycon tys
588                 . mkConApp data_con
589                 $ map Type tys ++ map Var (len_var : repr_vars)
590
591     to_repr [len_var]
592             [[repr_var]]
593             (EnumRepr { enum_arr_tycon    = tycon
594                       , enum_arr_data_con = data_con })
595       = return . wrapFamInstBody tycon []
596                $ mkConApp data_con [Var len_var, Var repr_var]
597
598     to_prod repr_vars@(r : _)
599             (ProdRepr { prod_components   = tys@(ty : _)
600                       , prod_arr_tycon    = tycon
601                       , prod_arr_data_con = data_con })
602       = do
603           len <- lengthPA ty (Var r)
604           return . wrapFamInstBody tycon tys
605                  . mkConApp data_con
606                  $ map Type tys ++ len : map Var repr_vars
607
608     to_prod [var] (IdRepr ty)   = return (Var var)
609     to_prod [var] (VoidRepr {}) = return (Var var)
610
611
612 buildFromArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
613 buildFromArrPRepr repr vect_tc prepr_tc arr_tc
614   = do
615       arg_ty     <- mkPArrayType =<< mkPReprType el_ty
616       arg        <- newLocalVar FSLIT("xs") arg_ty
617
618       res_ty     <- mkPArrayType el_ty
619
620       shape_vars <- arrShapeVars repr
621       repr_vars  <- arrReprVars  repr
622
623       parray_co  <- mkBuiltinCo parrayTyCon
624
625       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
626           co           = mkAppCoercion parray_co
627                        $ mkTyConApp repr_co var_tys
628
629           scrut  = mkCoerce co (Var arg)
630
631           result = wrapFamInstBody arr_tc var_tys
632                  . mkConApp arr_dc
633                  $ map Type var_tys ++ map Var (shape_vars ++ concat repr_vars)
634
635       liftM (Lam arg)
636             (from_repr repr scrut shape_vars repr_vars res_ty result)
637   where
638     var_tys = mkTyVarTys $ tyConTyVars vect_tc
639     el_ty   = mkTyConApp vect_tc var_tys
640
641     [arr_dc] = tyConDataCons arr_tc
642
643     from_repr (SumRepr { sum_components   = prods
644                        , sum_arr_tycon    = tycon
645                        , sum_arr_data_con = data_con })
646               expr
647               shape_vars
648               repr_vars
649               res_ty
650               body
651       = do
652           vars <- mapM (newLocalVar FSLIT("xs")) =<< mapM arrReprType prods
653           result <- go prods repr_vars vars body
654
655           let scrut = unwrapFamInstScrut tycon ty_args expr
656           return . Case scrut (mkWildId scrut_ty) res_ty
657                  $ [(DataAlt data_con, shape_vars ++ vars, result)]
658       where
659         ty_args  = map reprType prods
660         scrut_ty = mkTyConApp tycon ty_args
661
662         go [] [] [] body = return body
663         go (prod : prods) (repr_vars : rss) (var : vars) body
664           = do
665               shape_vars <- mapM (newLocalVar FSLIT("s")) =<< arrShapeTys prod
666
667               from_prod prod (Var var) shape_vars repr_vars res_ty
668                 =<< go prods rss vars body
669
670     from_repr repr expr shape_vars [repr_vars] res_ty body
671       = from_prod repr expr shape_vars repr_vars res_ty body
672
673     from_prod prod@(ProdRepr { prod_components = tys
674                              , prod_arr_tycon  = tycon
675                              , prod_arr_data_con = data_con })
676               expr
677               shape_vars
678               repr_vars
679               res_ty
680               body
681       = do
682           let scrut    = unwrapFamInstScrut tycon tys expr
683               scrut_ty = mkTyConApp tycon tys
684           ty <- arrReprType prod
685
686           return $ Case scrut (mkWildId scrut_ty) res_ty
687                    [(DataAlt data_con, shape_vars ++ repr_vars, body)]
688
689     from_prod (EnumRepr { enum_arr_tycon = tycon
690                         , enum_arr_data_con = data_con })
691               expr
692               [len_var]
693               [repr_var]
694               res_ty
695               body
696       = let scrut    = unwrapFamInstScrut tycon [] expr
697             scrut_ty = mkTyConApp tycon []
698         in
699         return $ Case scrut (mkWildId scrut_ty) res_ty
700                  [(DataAlt data_con, [len_var, repr_var], body)]
701
702     from_prod (IdRepr ty)
703               expr
704               shape_vars
705               [repr_var]
706               res_ty
707               body
708       = return $ Let (NonRec repr_var expr) body
709
710     from_prod (VoidRepr {})
711               expr
712               shape_vars
713               [repr_var]
714               res_ty
715               body
716       = return $ Let (NonRec repr_var expr) body
717
718 buildPRDictRepr :: Repr -> VM CoreExpr
719 buildPRDictRepr (VoidRepr { void_tycon = tycon })
720   = prDFunOfTyCon tycon
721 buildPRDictRepr (IdRepr ty) = mkPR ty
722 buildPRDictRepr (ProdRepr {
723                    prod_components = tys
724                  , prod_tycon      = tycon
725                  })
726   = do
727       prs  <- mapM mkPR tys
728       dfun <- prDFunOfTyCon tycon
729       return $ dfun `mkTyApps` tys `mkApps` prs
730
731 buildPRDictRepr (SumRepr {
732                    sum_components = prods
733                  , sum_tycon      = tycon })
734   = do
735       prs  <- mapM buildPRDictRepr prods
736       dfun <- prDFunOfTyCon tycon
737       return $ dfun `mkTyApps` map reprType prods `mkApps` prs
738
739 buildPRDictRepr (EnumRepr { enum_tycon = tycon })
740   = prDFunOfTyCon tycon
741
742 buildPRDict :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
743 buildPRDict repr vect_tc prepr_tc _
744   = do
745       dict  <- buildPRDictRepr repr
746
747       pr_co <- mkBuiltinCo prTyCon
748       let co = mkAppCoercion pr_co
749              . mkSymCoercion
750              $ mkTyConApp arg_co var_tys
751
752       return $ mkCoerce co dict
753   where
754     var_tys = mkTyVarTys $ tyConTyVars vect_tc
755
756     Just arg_co = tyConFamilyCoercion_maybe prepr_tc
757
758 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
759 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
760   do
761     name'  <- cloneName mkPArrayTyConOcc orig_name
762     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
763     parray <- builtin parrayTyCon
764
765     liftDs $ buildAlgTyCon name'
766                            tyvars
767                            []          -- no stupid theta
768                            rhs
769                            rec_flag    -- FIXME: is this ok?
770                            False       -- FIXME: no generics
771                            False       -- not GADT syntax
772                            (Just $ mk_fam_inst parray vect_tc)
773   where
774     orig_name = tyConName orig_tc
775     tyvars = tyConTyVars vect_tc
776     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
777
778
779 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
780 buildPArrayTyConRhs orig_name vect_tc repr_tc
781   = do
782       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
783       return $ DataTyCon { data_cons = [data_con], is_enum = False }
784
785 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
786 buildPArrayDataCon orig_name vect_tc repr_tc
787   = do
788       dc_name  <- cloneName mkPArrayDataConOcc orig_name
789       repr     <- mkRepr vect_tc
790
791       shape_tys <- arrShapeTys repr
792       repr_tys  <- arrReprTys  repr
793
794       let tys = shape_tys ++ repr_tys
795
796       liftDs $ buildDataCon dc_name
797                             False                  -- not infix
798                             (map (const NotMarkedStrict) tys)
799                             []                     -- no field labels
800                             (tyConTyVars vect_tc)
801                             []                     -- no existentials
802                             []                     -- no eq spec
803                             []                     -- no context
804                             tys
805                             repr_tc
806
807 mkPADFun :: TyCon -> VM Var
808 mkPADFun vect_tc
809   = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
810
811 buildTyConBindings :: TyCon -> TyCon -> TyCon -> TyCon -> Var
812                    -> VM [(Var, CoreExpr)]
813 buildTyConBindings orig_tc vect_tc prepr_tc arr_tc dfun
814   = do
815       repr  <- mkRepr vect_tc
816       vectDataConWorkers repr orig_tc vect_tc arr_tc
817       dict <- buildPADict repr vect_tc prepr_tc arr_tc dfun
818       binds <- takeHoisted
819       return $ (dfun, dict) : binds
820   where
821     orig_dcs = tyConDataCons orig_tc
822     vect_dcs = tyConDataCons vect_tc
823     [arr_dc] = tyConDataCons arr_tc
824
825     repr_tys = map dataConRepArgTys vect_dcs
826
827 vectDataConWorkers :: Repr -> TyCon -> TyCon -> TyCon
828                    -> VM ()
829 vectDataConWorkers repr orig_tc vect_tc arr_tc
830   = do
831       bs <- sequence
832           . zipWith3 def_worker  (tyConDataCons orig_tc) rep_tys
833           $ zipWith4 mk_data_con (tyConDataCons vect_tc)
834                                  rep_tys
835                                  (inits reprs)
836                                  (tail $ tails reprs)
837       mapM_ (uncurry hoistBinding) bs
838   where
839     tyvars   = tyConTyVars vect_tc
840     var_tys  = mkTyVarTys tyvars
841     ty_args  = map Type var_tys
842
843     res_ty   = mkTyConApp vect_tc var_tys
844
845     rep_tys  = map dataConRepArgTys $ tyConDataCons vect_tc
846     reprs    = splitSumRepr repr
847
848     [arr_dc] = tyConDataCons arr_tc
849
850     mk_data_con con tys pre post
851       = liftM2 (,) (vect_data_con con)
852                    (lift_data_con tys pre post (mkDataConTag con))
853
854     vect_data_con con = return $ mkConApp con ty_args
855     lift_data_con tys pre_reprs post_reprs tag
856       = do
857           len  <- builtin liftingContext
858           args <- mapM (newLocalVar FSLIT("xs"))
859                   =<< mapM mkPArrayType tys
860
861           shape <- replicateShape repr (Var len) tag
862           repr  <- mk_arr_repr (Var len) (map Var args)
863
864           pre   <- liftM concat $ mapM emptyArrRepr pre_reprs
865           post  <- liftM concat $ mapM emptyArrRepr post_reprs
866
867           return . mkLams (len : args)
868                  . wrapFamInstBody arr_tc var_tys
869                  . mkConApp arr_dc
870                  $ ty_args ++ shape ++ pre ++ repr ++ post
871
872     mk_arr_repr len []
873       = do
874           units <- replicatePA len (Var unitDataConId)
875           return [units]
876
877     mk_arr_repr len arrs = return arrs
878
879     def_worker data_con arg_tys mk_body
880       = do
881           body <- closedV
882                 . inBind orig_worker
883                 . polyAbstract tyvars $ \abstract ->
884                   liftM (abstract . vectorised)
885                 $ buildClosures tyvars [] arg_tys res_ty mk_body
886
887           vect_worker <- cloneId mkVectOcc orig_worker (exprType body)
888           defGlobalVar orig_worker vect_worker
889           return (vect_worker, body)
890       where
891         orig_worker = dataConWorkId data_con
892
893 buildPADict :: Repr -> TyCon -> TyCon -> TyCon -> Var -> VM CoreExpr
894 buildPADict repr vect_tc prepr_tc arr_tc dfun
895   = polyAbstract tvs $ \abstract ->
896     do
897       meth_binds <- mapM (mk_method repr) paMethods
898       let meth_exprs = map (Var . fst) meth_binds
899
900       pa_dc <- builtin paDataCon
901       let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
902           body = Let (Rec meth_binds) dict
903       return . mkInlineMe $ abstract body
904   where
905     tvs = tyConTyVars arr_tc
906     arg_tys = mkTyVarTys tvs
907
908     mk_method repr (name, build)
909       = localV
910       $ do
911           body <- build repr vect_tc prepr_tc arr_tc
912           var  <- newLocalVar name (exprType body)
913           return (var, mkInlineMe body)
914
915 paMethods = [(FSLIT("toPRepr"),      buildToPRepr),
916              (FSLIT("fromPRepr"),    buildFromPRepr),
917              (FSLIT("toArrPRepr"),   buildToArrPRepr),
918              (FSLIT("fromArrPRepr"), buildFromArrPRepr),
919              (FSLIT("dictPRepr"),    buildPRDict)]
920
921 -- | Split the given tycons into two sets depending on whether they have to be
922 -- converted (first list) or not (second list). The first argument contains
923 -- information about the conversion status of external tycons:
924 --
925 --   * tycons which have converted versions are mapped to True
926 --   * tycons which are not changed by vectorisation are mapped to False
927 --   * tycons which can't be converted are not elements of the map
928 --
929 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
930 classifyTyCons = classify [] []
931   where
932     classify conv keep cs [] = (conv, keep)
933     classify conv keep cs ((tcs, ds) : rs)
934       | can_convert && must_convert
935         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
936       | can_convert
937         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
938       | otherwise
939         = classify conv keep cs rs
940       where
941         refs = ds `delListFromUniqSet` tcs
942
943         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
944         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
945
946         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
947
948 -- | Compute mutually recursive groups of tycons in topological order
949 --
950 tyConGroups :: [TyCon] -> [TyConGroup]
951 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
952   where
953     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
954                                 , let ds = tyConsOfTyCon tc]
955
956     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
957     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
958       where
959         (tcs, dss) = unzip els
960
961 tyConsOfTyCon :: TyCon -> UniqSet TyCon
962 tyConsOfTyCon
963   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
964
965 tyConsOfType :: Type -> UniqSet TyCon
966 tyConsOfType ty
967   | Just ty' <- coreView ty    = tyConsOfType ty'
968 tyConsOfType (TyVarTy v)       = emptyUniqSet
969 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
970   where
971     extend | isUnLiftedTyCon tc
972            || isTupleTyCon   tc = id
973
974            | otherwise          = (`addOneToUniqSet` tc)
975
976 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
977 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
978                                  `addOneToUniqSet` funTyCon
979 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
980 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
981
982 tyConsOfTypes :: [Type] -> UniqSet TyCon
983 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
984