Vectorisation utilities
[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 -> [a] -> a
367 arrSelector (SumRepr {}) [_, sel, _] = sel
368 arrSelector _ _ = panic "arrSelector"
369
370 emptyArrRepr :: Repr -> VM [CoreExpr]
371 emptyArrRepr (SumRepr { sum_components = prods })
372   = liftM concat $ mapM emptyArrRepr prods
373 emptyArrRepr (ProdRepr { prod_components = [] })
374   = return [Var unitDataConId]
375 emptyArrRepr (ProdRepr { prod_components = tys })
376   = mapM emptyPA tys
377 emptyArrRepr (IdRepr ty)
378   = liftM singleton $ emptyPA ty
379 emptyArrRepr (VoidRepr { void_tycon = tycon })
380   = liftM singleton $ emptyPA (mkTyConApp tycon [])
381 emptyArrRepr (EnumRepr { enum_tycon = tycon })
382   = liftM singleton $ emptyPA (mkTyConApp tycon [])
383
384 arrReprTys :: Repr -> VM [Type]
385 arrReprTys (SumRepr { sum_components = reprs })
386   = liftM concat $ mapM arrReprTys reprs
387 arrReprTys (ProdRepr { prod_components = [] })
388   = return [unitTy]
389 arrReprTys (ProdRepr { prod_components = tys })
390   = mapM mkPArrayType tys
391 arrReprTys (IdRepr ty)
392   = liftM singleton $ mkPArrayType ty
393 arrReprTys (VoidRepr { void_tycon = tycon })
394   = liftM singleton $ mkPArrayType (mkTyConApp tycon [])
395 arrReprTys (EnumRepr {})
396   = liftM singleton $ mkPArrayType intPrimTy
397
398 arrReprTys' :: Repr -> VM [[Type]]
399 arrReprTys' (SumRepr { sum_components = reprs })
400   = mapM arrReprTys reprs
401 arrReprTys' repr = liftM singleton $ arrReprTys repr
402
403 arrReprVars :: Repr -> VM [[Var]]
404 arrReprVars repr
405   = mapM (mapM (newLocalVar FSLIT("rs"))) =<< arrReprTys' repr
406
407 mkRepr :: TyCon -> VM Repr
408 mkRepr vect_tc
409   | [tys] <- rep_tys = boxedProductRepr tys
410   | all null rep_tys = enumRepr
411   | otherwise        = sumRepr =<< mapM unboxedProductRepr rep_tys
412   where
413     rep_tys = map dataConRepArgTys $ tyConDataCons vect_tc
414
415 buildPReprType :: TyCon -> VM Type
416 buildPReprType = liftM reprType . mkRepr
417
418 buildToPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
419 buildToPRepr repr vect_tc prepr_tc _
420   = do
421       arg    <- newLocalVar FSLIT("x") arg_ty
422       result <- to_repr repr (Var arg)
423
424       return . Lam arg
425              . wrapFamInstBody prepr_tc var_tys
426              $ result
427   where
428     var_tys = mkTyVarTys $ tyConTyVars vect_tc
429     arg_ty  = mkTyConApp vect_tc var_tys
430     res_ty  = reprType repr
431
432     cons    = tyConDataCons vect_tc
433     [con]   = cons
434
435     to_repr (SumRepr { sum_components = prods
436                      , sum_tycon      = tycon })
437             expr
438       = do
439           (vars, bodies) <- mapAndUnzipM to_unboxed prods
440           return . Case expr (mkWildId (exprType expr)) res_ty
441                  $ zipWith4 mk_alt cons vars (tyConDataCons tycon) bodies
442       where
443         mk_alt con vars sum_con body
444           = (DataAlt con, vars, mkConApp sum_con (ty_args ++ [body]))
445
446         ty_args = map (Type . reprType) prods
447
448     to_repr (EnumRepr { enum_data_con = data_con }) expr
449       = return . Case expr (mkWildId (exprType expr)) res_ty
450                $ map mk_alt cons
451       where
452         mk_alt con = (DataAlt con, [], mkConApp data_con [mkDataConTag con])
453
454     to_repr prod expr
455       = do
456           (vars, body) <- to_unboxed prod
457           return $ Case expr (mkWildId (exprType expr)) res_ty
458                    [(DataAlt con, vars, body)]
459
460     to_unboxed (ProdRepr { prod_components = tys
461                          , prod_data_con   = data_con })
462       = do
463           vars <- mapM (newLocalVar FSLIT("r")) tys
464           return (vars, mkConApp data_con (map Type tys ++ map Var vars))
465
466     to_unboxed (IdRepr ty)
467       = do
468           var <- newLocalVar FSLIT("y") ty
469           return ([var], Var var)
470
471     to_unboxed (VoidRepr { void_bottom = bottom })
472       = return ([], bottom)
473
474
475 buildFromPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
476 buildFromPRepr repr vect_tc prepr_tc _
477   = do
478       arg_ty <- mkPReprType res_ty
479       arg    <- newLocalVar FSLIT("x") arg_ty
480
481       liftM (Lam arg)
482            . from_repr repr
483            $ unwrapFamInstScrut prepr_tc var_tys (Var arg)
484   where
485     var_tys = mkTyVarTys $ tyConTyVars vect_tc
486     res_ty  = mkTyConApp vect_tc var_tys
487
488     cons    = map (`mkConApp` map Type var_tys) (tyConDataCons vect_tc)
489     [con]   = cons
490
491     from_repr repr@(SumRepr { sum_components = prods
492                             , sum_tycon      = tycon })
493               expr
494       = do
495           vars   <- mapM (newLocalVar FSLIT("x")) (map reprType prods)
496           bodies <- sequence . zipWith3 from_unboxed prods cons
497                              $ map Var vars
498           return . Case expr (mkWildId (reprType repr)) res_ty
499                  $ zipWith3 sum_alt (tyConDataCons tycon) vars bodies
500       where
501         sum_alt data_con var body = (DataAlt data_con, [var], body)
502
503     from_repr repr@(EnumRepr { enum_data_con = data_con }) expr
504       = do
505           var <- newLocalVar FSLIT("n") intPrimTy
506
507           let res = Case (Var var) (mkWildId intPrimTy) res_ty
508                   $ (DEFAULT, [], error_expr)
509                   : zipWith mk_alt (tyConDataCons vect_tc) cons
510
511           return $ Case expr (mkWildId (reprType repr)) res_ty
512                    [(DataAlt data_con, [var], res)]
513       where
514         mk_alt data_con con = (LitAlt (mkDataConTagLit data_con), [], con)
515
516         error_expr = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty
517                    . showSDoc
518                    $ sep [text "Invalid NDP representation of", ppr vect_tc]
519
520     from_repr repr expr = from_unboxed repr con expr
521
522     from_unboxed prod@(ProdRepr { prod_components = tys
523                                 , prod_data_con   = data_con })
524               con
525               expr
526       = do
527           vars <- mapM (newLocalVar FSLIT("y")) tys
528           return $ Case expr (mkWildId (reprType prod)) res_ty
529                    [(DataAlt data_con, vars, con `mkVarApps` vars)]
530
531     from_unboxed (IdRepr _) con expr
532        = return $ con `App` expr
533
534     from_unboxed (VoidRepr {}) con expr
535        = return con
536
537 buildToArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
538 buildToArrPRepr repr vect_tc prepr_tc arr_tc
539   = do
540       arg_ty     <- mkPArrayType el_ty
541       arg        <- newLocalVar FSLIT("xs") arg_ty
542
543       res_ty     <- mkPArrayType (reprType repr)
544
545       shape_vars <- arrShapeVars repr
546       repr_vars  <- arrReprVars  repr
547
548       parray_co  <- mkBuiltinCo parrayTyCon
549
550       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
551           co           = mkAppCoercion parray_co
552                        . mkSymCoercion
553                        $ mkTyConApp repr_co var_tys
554
555           scrut   = unwrapFamInstScrut arr_tc var_tys (Var arg)
556
557       result <- to_repr shape_vars repr_vars repr
558
559       return . Lam arg
560              . mkCoerce co
561              $ Case scrut (mkWildId (mkTyConApp arr_tc var_tys)) res_ty
562                [(DataAlt arr_dc, shape_vars ++ concat repr_vars, result)]
563   where
564     var_tys = mkTyVarTys $ tyConTyVars vect_tc
565     el_ty   = mkTyConApp vect_tc var_tys
566
567     [arr_dc] = tyConDataCons arr_tc
568
569     to_repr shape_vars@(len_var : _)
570             repr_vars
571             (SumRepr { sum_components   = prods
572                      , sum_arr_tycon    = tycon
573                      , sum_arr_data_con = data_con })
574       = do
575           exprs <- zipWithM to_prod repr_vars prods
576
577           return . wrapFamInstBody tycon tys
578                  . mkConApp data_con
579                  $ map Type tys ++ map Var shape_vars ++ exprs
580       where
581         tys = map reprType prods
582
583     to_repr [len_var]
584             [repr_vars]
585             (ProdRepr { prod_components   = tys
586                       , prod_arr_tycon    = tycon
587                       , prod_arr_data_con = data_con })
588        = return . wrapFamInstBody tycon tys
589                 . mkConApp data_con
590                 $ map Type tys ++ map Var (len_var : repr_vars)
591
592     to_repr [len_var]
593             [[repr_var]]
594             (EnumRepr { enum_arr_tycon    = tycon
595                       , enum_arr_data_con = data_con })
596       = return . wrapFamInstBody tycon []
597                $ mkConApp data_con [Var len_var, Var repr_var]
598
599     to_prod repr_vars@(r : _)
600             (ProdRepr { prod_components   = tys@(ty : _)
601                       , prod_arr_tycon    = tycon
602                       , prod_arr_data_con = data_con })
603       = do
604           len <- lengthPA ty (Var r)
605           return . wrapFamInstBody tycon tys
606                  . mkConApp data_con
607                  $ map Type tys ++ len : map Var repr_vars
608
609     to_prod [var] (IdRepr ty)   = return (Var var)
610     to_prod [var] (VoidRepr {}) = return (Var var)
611
612
613 buildFromArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
614 buildFromArrPRepr repr vect_tc prepr_tc arr_tc
615   = do
616       arg_ty     <- mkPArrayType =<< mkPReprType el_ty
617       arg        <- newLocalVar FSLIT("xs") arg_ty
618
619       res_ty     <- mkPArrayType el_ty
620
621       shape_vars <- arrShapeVars repr
622       repr_vars  <- arrReprVars  repr
623
624       parray_co  <- mkBuiltinCo parrayTyCon
625
626       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
627           co           = mkAppCoercion parray_co
628                        $ mkTyConApp repr_co var_tys
629
630           scrut  = mkCoerce co (Var arg)
631
632           result = wrapFamInstBody arr_tc var_tys
633                  . mkConApp arr_dc
634                  $ map Type var_tys ++ map Var (shape_vars ++ concat repr_vars)
635
636       liftM (Lam arg)
637             (from_repr repr scrut shape_vars repr_vars res_ty result)
638   where
639     var_tys = mkTyVarTys $ tyConTyVars vect_tc
640     el_ty   = mkTyConApp vect_tc var_tys
641
642     [arr_dc] = tyConDataCons arr_tc
643
644     from_repr (SumRepr { sum_components   = prods
645                        , sum_arr_tycon    = tycon
646                        , sum_arr_data_con = data_con })
647               expr
648               shape_vars
649               repr_vars
650               res_ty
651               body
652       = do
653           vars <- mapM (newLocalVar FSLIT("xs")) =<< mapM arrReprType prods
654           result <- go prods repr_vars vars body
655
656           let scrut = unwrapFamInstScrut tycon ty_args expr
657           return . Case scrut (mkWildId scrut_ty) res_ty
658                  $ [(DataAlt data_con, shape_vars ++ vars, result)]
659       where
660         ty_args  = map reprType prods
661         scrut_ty = mkTyConApp tycon ty_args
662
663         go [] [] [] body = return body
664         go (prod : prods) (repr_vars : rss) (var : vars) body
665           = do
666               shape_vars <- mapM (newLocalVar FSLIT("s")) =<< arrShapeTys prod
667
668               from_prod prod (Var var) shape_vars repr_vars res_ty
669                 =<< go prods rss vars body
670
671     from_repr repr expr shape_vars [repr_vars] res_ty body
672       = from_prod repr expr shape_vars repr_vars res_ty body
673
674     from_prod prod@(ProdRepr { prod_components = tys
675                              , prod_arr_tycon  = tycon
676                              , prod_arr_data_con = data_con })
677               expr
678               shape_vars
679               repr_vars
680               res_ty
681               body
682       = do
683           let scrut    = unwrapFamInstScrut tycon tys expr
684               scrut_ty = mkTyConApp tycon tys
685           ty <- arrReprType prod
686
687           return $ Case scrut (mkWildId scrut_ty) res_ty
688                    [(DataAlt data_con, shape_vars ++ repr_vars, body)]
689
690     from_prod (EnumRepr { enum_arr_tycon = tycon
691                         , enum_arr_data_con = data_con })
692               expr
693               [len_var]
694               [repr_var]
695               res_ty
696               body
697       = let scrut    = unwrapFamInstScrut tycon [] expr
698             scrut_ty = mkTyConApp tycon []
699         in
700         return $ Case scrut (mkWildId scrut_ty) res_ty
701                  [(DataAlt data_con, [len_var, repr_var], body)]
702
703     from_prod (IdRepr ty)
704               expr
705               shape_vars
706               [repr_var]
707               res_ty
708               body
709       = return $ Let (NonRec repr_var expr) body
710
711     from_prod (VoidRepr {})
712               expr
713               shape_vars
714               [repr_var]
715               res_ty
716               body
717       = return $ Let (NonRec repr_var expr) body
718
719 buildPRDictRepr :: Repr -> VM CoreExpr
720 buildPRDictRepr (VoidRepr { void_tycon = tycon })
721   = prDFunOfTyCon tycon
722 buildPRDictRepr (IdRepr ty) = mkPR ty
723 buildPRDictRepr (ProdRepr {
724                    prod_components = tys
725                  , prod_tycon      = tycon
726                  })
727   = do
728       prs  <- mapM mkPR tys
729       dfun <- prDFunOfTyCon tycon
730       return $ dfun `mkTyApps` tys `mkApps` prs
731
732 buildPRDictRepr (SumRepr {
733                    sum_components = prods
734                  , sum_tycon      = tycon })
735   = do
736       prs  <- mapM buildPRDictRepr prods
737       dfun <- prDFunOfTyCon tycon
738       return $ dfun `mkTyApps` map reprType prods `mkApps` prs
739
740 buildPRDictRepr (EnumRepr { enum_tycon = tycon })
741   = prDFunOfTyCon tycon
742
743 buildPRDict :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
744 buildPRDict repr vect_tc prepr_tc _
745   = do
746       dict  <- buildPRDictRepr repr
747
748       pr_co <- mkBuiltinCo prTyCon
749       let co = mkAppCoercion pr_co
750              . mkSymCoercion
751              $ mkTyConApp arg_co var_tys
752
753       return $ mkCoerce co dict
754   where
755     var_tys = mkTyVarTys $ tyConTyVars vect_tc
756
757     Just arg_co = tyConFamilyCoercion_maybe prepr_tc
758
759 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
760 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
761   do
762     name'  <- cloneName mkPArrayTyConOcc orig_name
763     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
764     parray <- builtin parrayTyCon
765
766     liftDs $ buildAlgTyCon name'
767                            tyvars
768                            []          -- no stupid theta
769                            rhs
770                            rec_flag    -- FIXME: is this ok?
771                            False       -- FIXME: no generics
772                            False       -- not GADT syntax
773                            (Just $ mk_fam_inst parray vect_tc)
774   where
775     orig_name = tyConName orig_tc
776     tyvars = tyConTyVars vect_tc
777     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
778
779
780 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
781 buildPArrayTyConRhs orig_name vect_tc repr_tc
782   = do
783       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
784       return $ DataTyCon { data_cons = [data_con], is_enum = False }
785
786 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
787 buildPArrayDataCon orig_name vect_tc repr_tc
788   = do
789       dc_name  <- cloneName mkPArrayDataConOcc orig_name
790       repr     <- mkRepr vect_tc
791
792       shape_tys <- arrShapeTys repr
793       repr_tys  <- arrReprTys  repr
794
795       let tys = shape_tys ++ repr_tys
796
797       liftDs $ buildDataCon dc_name
798                             False                  -- not infix
799                             (map (const NotMarkedStrict) tys)
800                             []                     -- no field labels
801                             (tyConTyVars vect_tc)
802                             []                     -- no existentials
803                             []                     -- no eq spec
804                             []                     -- no context
805                             tys
806                             repr_tc
807
808 mkPADFun :: TyCon -> VM Var
809 mkPADFun vect_tc
810   = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
811
812 buildTyConBindings :: TyCon -> TyCon -> TyCon -> TyCon -> Var
813                    -> VM [(Var, CoreExpr)]
814 buildTyConBindings orig_tc vect_tc prepr_tc arr_tc dfun
815   = do
816       repr  <- mkRepr vect_tc
817       vectDataConWorkers repr orig_tc vect_tc arr_tc
818       dict <- buildPADict repr vect_tc prepr_tc arr_tc dfun
819       binds <- takeHoisted
820       return $ (dfun, dict) : binds
821   where
822     orig_dcs = tyConDataCons orig_tc
823     vect_dcs = tyConDataCons vect_tc
824     [arr_dc] = tyConDataCons arr_tc
825
826     repr_tys = map dataConRepArgTys vect_dcs
827
828 vectDataConWorkers :: Repr -> TyCon -> TyCon -> TyCon
829                    -> VM ()
830 vectDataConWorkers repr orig_tc vect_tc arr_tc
831   = do
832       bs <- sequence
833           . zipWith3 def_worker  (tyConDataCons orig_tc) rep_tys
834           $ zipWith4 mk_data_con (tyConDataCons vect_tc)
835                                  rep_tys
836                                  (inits reprs)
837                                  (tail $ tails reprs)
838       mapM_ (uncurry hoistBinding) bs
839   where
840     tyvars   = tyConTyVars vect_tc
841     var_tys  = mkTyVarTys tyvars
842     ty_args  = map Type var_tys
843
844     res_ty   = mkTyConApp vect_tc var_tys
845
846     rep_tys  = map dataConRepArgTys $ tyConDataCons vect_tc
847     reprs    = splitSumRepr repr
848
849     [arr_dc] = tyConDataCons arr_tc
850
851     mk_data_con con tys pre post
852       = liftM2 (,) (vect_data_con con)
853                    (lift_data_con tys pre post (mkDataConTag con))
854
855     vect_data_con con = return $ mkConApp con ty_args
856     lift_data_con tys pre_reprs post_reprs tag
857       = do
858           len  <- builtin liftingContext
859           args <- mapM (newLocalVar FSLIT("xs"))
860                   =<< mapM mkPArrayType tys
861
862           shape <- replicateShape repr (Var len) tag
863           repr  <- mk_arr_repr (Var len) (map Var args)
864
865           pre   <- liftM concat $ mapM emptyArrRepr pre_reprs
866           post  <- liftM concat $ mapM emptyArrRepr post_reprs
867
868           return . mkLams (len : args)
869                  . wrapFamInstBody arr_tc var_tys
870                  . mkConApp arr_dc
871                  $ ty_args ++ shape ++ pre ++ repr ++ post
872
873     mk_arr_repr len []
874       = do
875           units <- replicatePA len (Var unitDataConId)
876           return [units]
877
878     mk_arr_repr len arrs = return arrs
879
880     def_worker data_con arg_tys mk_body
881       = do
882           body <- closedV
883                 . inBind orig_worker
884                 . polyAbstract tyvars $ \abstract ->
885                   liftM (abstract . vectorised)
886                 $ buildClosures tyvars [] arg_tys res_ty mk_body
887
888           vect_worker <- cloneId mkVectOcc orig_worker (exprType body)
889           defGlobalVar orig_worker vect_worker
890           return (vect_worker, body)
891       where
892         orig_worker = dataConWorkId data_con
893
894 buildPADict :: Repr -> TyCon -> TyCon -> TyCon -> Var -> VM CoreExpr
895 buildPADict repr vect_tc prepr_tc arr_tc dfun
896   = polyAbstract tvs $ \abstract ->
897     do
898       meth_binds <- mapM (mk_method repr) paMethods
899       let meth_exprs = map (Var . fst) meth_binds
900
901       pa_dc <- builtin paDataCon
902       let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
903           body = Let (Rec meth_binds) dict
904       return . mkInlineMe $ abstract body
905   where
906     tvs = tyConTyVars arr_tc
907     arg_tys = mkTyVarTys tvs
908
909     mk_method repr (name, build)
910       = localV
911       $ do
912           body <- build repr vect_tc prepr_tc arr_tc
913           var  <- newLocalVar name (exprType body)
914           return (var, mkInlineMe body)
915
916 paMethods = [(FSLIT("toPRepr"),      buildToPRepr),
917              (FSLIT("fromPRepr"),    buildFromPRepr),
918              (FSLIT("toArrPRepr"),   buildToArrPRepr),
919              (FSLIT("fromArrPRepr"), buildFromArrPRepr),
920              (FSLIT("dictPRepr"),    buildPRDict)]
921
922 -- | Split the given tycons into two sets depending on whether they have to be
923 -- converted (first list) or not (second list). The first argument contains
924 -- information about the conversion status of external tycons:
925 --
926 --   * tycons which have converted versions are mapped to True
927 --   * tycons which are not changed by vectorisation are mapped to False
928 --   * tycons which can't be converted are not elements of the map
929 --
930 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
931 classifyTyCons = classify [] []
932   where
933     classify conv keep cs [] = (conv, keep)
934     classify conv keep cs ((tcs, ds) : rs)
935       | can_convert && must_convert
936         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
937       | can_convert
938         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
939       | otherwise
940         = classify conv keep cs rs
941       where
942         refs = ds `delListFromUniqSet` tcs
943
944         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
945         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
946
947         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
948
949 -- | Compute mutually recursive groups of tycons in topological order
950 --
951 tyConGroups :: [TyCon] -> [TyConGroup]
952 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
953   where
954     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
955                                 , let ds = tyConsOfTyCon tc]
956
957     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
958     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
959       where
960         (tcs, dss) = unzip els
961
962 tyConsOfTyCon :: TyCon -> UniqSet TyCon
963 tyConsOfTyCon
964   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
965
966 tyConsOfType :: Type -> UniqSet TyCon
967 tyConsOfType ty
968   | Just ty' <- coreView ty    = tyConsOfType ty'
969 tyConsOfType (TyVarTy v)       = emptyUniqSet
970 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
971   where
972     extend | isUnLiftedTyCon tc
973            || isTupleTyCon   tc = id
974
975            | otherwise          = (`addOneToUniqSet` tc)
976
977 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
978 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
979                                  `addOneToUniqSet` funTyCon
980 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
981 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
982
983 tyConsOfTypes :: [Type] -> UniqSet TyCon
984 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
985