Fix vectorisation of nullary data constructors
[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        ( unitTy, unitTyCon, intTy, intDataCon, unitDataConId )
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_, mapAndUnzipM )
40 import Data.List      ( inits, tails, zipWith4, zipWith5 )
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       repr_tcs <- zipWithM buildPReprTyCon   orig_tcs vect_tcs
101       parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
102       dfuns    <- mapM mkPADFun vect_tcs
103       defTyConPAs (zip vect_tcs dfuns)
104       binds    <- sequence (zipWith5 buildTyConBindings orig_tcs
105                                                         vect_tcs
106                                                         repr_tcs
107                                                         parr_tcs
108                                                         dfuns)
109
110       let all_new_tcs = new_tcs ++ repr_tcs ++ parr_tcs
111
112       let new_env = extendTypeEnvList env
113                        (map ATyCon all_new_tcs
114                         ++ [ADataCon dc | tc <- all_new_tcs
115                                         , dc <- tyConDataCons tc])
116
117       return (new_env, map mkLocalFamInst (repr_tcs ++ parr_tcs), concat binds)
118   where
119     tycons = typeEnvTyCons env
120     groups = tyConGroups tycons
121
122     mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
123
124     keep_tc tc = let dcs = tyConDataCons tc
125                  in
126                  defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
127
128
129 vectTyConDecls :: [TyCon] -> VM [TyCon]
130 vectTyConDecls tcs = fixV $ \tcs' ->
131   do
132     mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
133     mapM vectTyConDecl tcs
134   where
135     lazy_zip [] _ = []
136     lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
137
138 vectTyConDecl :: TyCon -> VM TyCon
139 vectTyConDecl tc
140   = do
141       name' <- cloneName mkVectTyConOcc name
142       rhs'  <- vectAlgTyConRhs (algTyConRhs tc)
143
144       liftDs $ buildAlgTyCon name'
145                              tyvars
146                              []           -- no stupid theta
147                              rhs'
148                              rec_flag     -- FIXME: is this ok?
149                              False        -- FIXME: no generics
150                              False        -- not GADT syntax
151                              Nothing      -- not a family instance
152   where
153     name   = tyConName tc
154     tyvars = tyConTyVars tc
155     rec_flag = boolToRecFlag (isRecursiveTyCon tc)
156
157 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
158 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
159                            , is_enum   = is_enum
160                            })
161   = do
162       data_cons' <- mapM vectDataCon data_cons
163       zipWithM_ defDataCon data_cons data_cons'
164       return $ DataTyCon { data_cons = data_cons'
165                          , is_enum   = is_enum
166                          }
167
168 vectDataCon :: DataCon -> VM DataCon
169 vectDataCon dc
170   | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
171   | not . null $ dataConEqSpec   dc = pprPanic "vectDataCon: eq spec" (ppr dc)
172   | otherwise
173   = do
174       name'    <- cloneName mkVectDataConOcc name
175       tycon'   <- vectTyCon tycon
176       arg_tys  <- mapM vectType rep_arg_tys
177
178       liftDs $ buildDataCon name'
179                             False           -- not infix
180                             (map (const NotMarkedStrict) arg_tys)
181                             []              -- no labelled fields
182                             univ_tvs
183                             []              -- no existential tvs for now
184                             []              -- no eq spec for now
185                             []              -- no context
186                             arg_tys
187                             tycon'
188   where
189     name        = dataConName dc
190     univ_tvs    = dataConUnivTyVars dc
191     rep_arg_tys = dataConRepArgTys dc
192     tycon       = dataConTyCon dc
193
194 mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
195 mk_fam_inst fam_tc arg_tc
196   = (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
197
198 buildPReprTyCon :: TyCon -> TyCon -> VM TyCon
199 buildPReprTyCon orig_tc vect_tc
200   = do
201       name     <- cloneName mkPReprTyConOcc (tyConName orig_tc)
202       rhs_ty   <- buildPReprType vect_tc
203       prepr_tc <- builtin preprTyCon
204       liftDs $ buildSynTyCon name
205                              tyvars
206                              (SynonymTyCon rhs_ty)
207                              (Just $ mk_fam_inst prepr_tc vect_tc)
208   where
209     tyvars = tyConTyVars vect_tc
210
211
212 data Repr = ProdRepr {
213               prod_components   :: [Type]
214             , prod_tycon        :: TyCon
215             , prod_data_con     :: DataCon
216             , prod_arr_tycon    :: TyCon
217             , prod_arr_data_con :: DataCon
218             }
219
220           | SumRepr {
221               sum_components    :: [Repr]
222             , sum_tycon         :: TyCon
223             , sum_arr_tycon     :: TyCon
224             , sum_arr_data_con  :: DataCon
225             }
226
227           | IdRepr Type
228
229           | VoidRepr {
230               void_tycon        :: TyCon
231             , void_bottom       :: CoreExpr
232             }
233
234 mkVoid :: VM Repr
235 mkVoid = do
236            tycon <- builtin voidTyCon
237            var   <- builtin voidVar
238            return $ VoidRepr {
239                       void_tycon  = tycon
240                     , void_bottom = Var var
241                     }
242
243 mkProduct :: [Type] -> VM Repr
244 mkProduct tys
245   = do
246       tycon <- builtin (prodTyCon arity)
247       let [data_con] = tyConDataCons tycon
248
249       (arr_tycon, _) <- parrayReprTyCon $ mkTyConApp tycon tys
250       let [arr_data_con] = tyConDataCons arr_tycon
251
252       return $ ProdRepr {
253                  prod_components   = tys
254                , prod_tycon        = tycon
255                , prod_data_con     = data_con
256                , prod_arr_tycon    = arr_tycon
257                , prod_arr_data_con = arr_data_con
258                }
259   where
260     arity = length tys
261
262 mkSubProduct :: [Type] -> VM Repr
263 mkSubProduct []   = mkVoid
264 mkSubProduct [ty] = return $ IdRepr ty
265 mkSubProduct tys  = mkProduct tys
266
267 mkSum :: [Repr] -> VM Repr
268 mkSum [repr] = return repr
269 mkSum reprs
270   = do
271       tycon <- builtin (sumTyCon arity)
272       (arr_tycon, _) <- parrayReprTyCon
273                       . mkTyConApp tycon
274                       $ map reprType reprs
275
276       let [arr_data_con] = tyConDataCons arr_tycon
277
278       return $ SumRepr {
279                  sum_components   = reprs
280                , sum_tycon        = tycon
281                , sum_arr_tycon    = arr_tycon
282                , sum_arr_data_con = arr_data_con
283                }
284   where
285     arity = length reprs
286
287 reprType :: Repr -> Type
288 reprType (ProdRepr { prod_tycon = tycon, prod_components = tys })
289   = mkTyConApp tycon tys
290 reprType (SumRepr { sum_tycon = tycon, sum_components = reprs })
291   = mkTyConApp tycon (map reprType reprs)
292 reprType (IdRepr ty) = ty
293 reprType (VoidRepr { void_tycon = tycon }) = mkTyConApp tycon []
294
295 arrReprType :: Repr -> VM Type
296 arrReprType = mkPArrayType . reprType
297
298 arrShapeTys :: Repr -> VM [Type]
299 arrShapeTys (SumRepr  {})
300   = do
301       int_arr <- builtin parrayIntPrimTyCon
302       return [intPrimTy, mkTyConApp int_arr [], mkTyConApp int_arr []]
303 arrShapeTys (ProdRepr {}) = return [intPrimTy]
304 arrShapeTys (IdRepr _)    = return []
305 arrShapeTys (VoidRepr {}) = return [intPrimTy]
306
307 arrShapeVars :: Repr -> VM [Var]
308 arrShapeVars repr = mapM (newLocalVar FSLIT("sh")) =<< arrShapeTys repr
309
310 replicateShape :: Repr -> CoreExpr -> CoreExpr -> VM [CoreExpr]
311 replicateShape (ProdRepr {}) len _ = return [len]
312 replicateShape (SumRepr {})  len tag
313   = do
314       rep <- builtin replicatePAIntPrimVar
315       up  <- builtin upToPAIntPrimVar
316       return [len, Var rep `mkApps` [len, tag], Var up `App` len]
317 replicateShape (IdRepr _) _ _ = return []
318 replicateShape (VoidRepr {}) len _ = return [len]
319
320 arrReprElemTys :: Repr -> VM [[Type]]
321 arrReprElemTys (SumRepr { sum_components = prods })
322   = mapM arrProdElemTys prods
323 arrReprElemTys prod@(ProdRepr {})
324   = do
325       tys <- arrProdElemTys prod
326       return [tys]
327 arrReprElemTys (IdRepr ty) = return [[ty]]
328 arrReprElemTys (VoidRepr { void_tycon = tycon })
329   = return [[mkTyConApp tycon []]]
330
331 arrProdElemTys (ProdRepr { prod_components = [] })
332   = do
333       void <- builtin voidTyCon
334       return [mkTyConApp void []]
335 arrProdElemTys (ProdRepr { prod_components = tys })
336   = return tys
337 arrProdElemTys (IdRepr ty) = return [ty]
338 arrProdElemTys (VoidRepr { void_tycon = tycon })
339   = return [mkTyConApp tycon []]
340
341 arrReprTys :: Repr -> VM [[Type]]
342 arrReprTys repr = mapM (mapM mkPArrayType) =<< arrReprElemTys repr
343
344 arrReprVars :: Repr -> VM [[Var]]
345 arrReprVars repr
346   = mapM (mapM (newLocalVar FSLIT("rs"))) =<< arrReprTys repr
347
348 mkRepr :: TyCon -> VM Repr
349 mkRepr vect_tc
350   | [tys] <- rep_tys = mkProduct tys
351   | otherwise        = mkSum =<< mapM mkSubProduct rep_tys
352   where
353     rep_tys = map dataConRepArgTys $ tyConDataCons vect_tc
354
355 buildPReprType :: TyCon -> VM Type
356 buildPReprType = liftM reprType . mkRepr
357
358 buildToPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
359 buildToPRepr repr vect_tc prepr_tc _
360   = do
361       arg    <- newLocalVar FSLIT("x") arg_ty
362       result <- to_repr repr (Var arg)
363
364       return . Lam arg
365              . wrapFamInstBody prepr_tc var_tys
366              $ result
367   where
368     var_tys = mkTyVarTys $ tyConTyVars vect_tc
369     arg_ty  = mkTyConApp vect_tc var_tys
370     res_ty  = reprType repr
371
372     cons    = tyConDataCons vect_tc
373     [con]   = cons
374
375     to_repr (SumRepr { sum_components = prods
376                      , sum_tycon      = tycon })
377             expr
378       = do
379           (vars, bodies) <- mapAndUnzipM prod_alt prods
380           return . Case expr (mkWildId (exprType expr)) res_ty
381                  $ zipWith4 mk_alt cons vars (tyConDataCons tycon) bodies
382       where
383         mk_alt con vars sum_con body
384           = (DataAlt con, vars, mkConApp sum_con (ty_args ++ [body]))
385
386         ty_args = map (Type . reprType) prods
387
388     to_repr prod expr
389       = do
390           (vars, body) <- prod_alt prod
391           return $ Case expr (mkWildId (exprType expr)) res_ty
392                    [(DataAlt con, vars, body)]
393
394     prod_alt (ProdRepr { prod_components = tys
395                        , prod_data_con   = data_con })
396       = do
397           vars <- mapM (newLocalVar FSLIT("r")) tys
398           return (vars, mkConApp data_con (map Type tys ++ map Var vars))
399
400     prod_alt (IdRepr ty)
401       = do
402           var <- newLocalVar FSLIT("y") ty
403           return ([var], Var var)
404
405     prod_alt (VoidRepr { void_bottom = bottom })
406       = return ([], bottom)
407
408
409 buildFromPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
410 buildFromPRepr repr vect_tc prepr_tc _
411   = do
412       arg_ty <- mkPReprType res_ty
413       arg    <- newLocalVar FSLIT("x") arg_ty
414
415       liftM (Lam arg)
416            . from_repr repr
417            $ unwrapFamInstScrut prepr_tc var_tys (Var arg)
418   where
419     var_tys = mkTyVarTys $ tyConTyVars vect_tc
420     res_ty  = mkTyConApp vect_tc var_tys
421
422     cons    = map (`mkConApp` map Type var_tys) (tyConDataCons vect_tc)
423     [con]   = cons
424
425     from_repr repr@(SumRepr { sum_components = prods
426                             , sum_tycon      = tycon })
427               expr
428       = do
429           vars   <- mapM (newLocalVar FSLIT("x")) (map reprType prods)
430           bodies <- sequence . zipWith3 from_prod prods cons
431                              $ map Var vars
432           return . Case expr (mkWildId (reprType repr)) res_ty
433                  $ zipWith3 sum_alt (tyConDataCons tycon) vars bodies
434       where
435         sum_alt data_con var body = (DataAlt data_con, [var], body)
436
437     from_repr repr expr = from_prod repr con expr
438
439     from_prod prod@(ProdRepr { prod_components = tys
440                              , prod_data_con   = data_con })
441               con
442               expr
443       = do
444           vars <- mapM (newLocalVar FSLIT("y")) tys
445           return $ Case expr (mkWildId (reprType prod)) res_ty
446                    [(DataAlt data_con, vars, con `mkVarApps` vars)]
447
448     from_prod (IdRepr _) con expr
449        = return $ con `App` expr
450
451     from_prod (VoidRepr {}) con expr
452        = return con
453
454 buildToArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
455 buildToArrPRepr repr vect_tc prepr_tc arr_tc
456   = do
457       arg_ty     <- mkPArrayType el_ty
458       arg        <- newLocalVar FSLIT("xs") arg_ty
459
460       res_ty     <- mkPArrayType (reprType repr)
461
462       shape_vars <- arrShapeVars repr
463       repr_vars  <- arrReprVars  repr
464
465       parray_co  <- mkBuiltinCo parrayTyCon
466
467       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
468           co           = mkAppCoercion parray_co
469                        . mkSymCoercion
470                        $ mkTyConApp repr_co var_tys
471
472           scrut   = unwrapFamInstScrut arr_tc var_tys (Var arg)
473
474       result <- to_repr shape_vars repr_vars repr
475
476       return . Lam arg
477              . mkCoerce co
478              $ Case scrut (mkWildId (mkTyConApp arr_tc var_tys)) res_ty
479                [(DataAlt arr_dc, shape_vars ++ concat repr_vars, result)]
480   where
481     var_tys = mkTyVarTys $ tyConTyVars vect_tc
482     el_ty   = mkTyConApp vect_tc var_tys
483
484     [arr_dc] = tyConDataCons arr_tc
485
486     to_repr shape_vars@(len_var : _)
487             repr_vars
488             (SumRepr { sum_components   = prods
489                      , sum_arr_tycon    = tycon
490                      , sum_arr_data_con = data_con })
491       = do
492           exprs <- zipWithM to_prod repr_vars prods
493
494           return . wrapFamInstBody tycon tys
495                  . mkConApp data_con
496                  $ map Type tys ++ map Var shape_vars ++ exprs
497       where
498         tys = map reprType prods
499
500     to_repr [len_var]
501             [repr_vars]
502             (ProdRepr { prod_components   = tys
503                       , prod_arr_tycon    = tycon
504                       , prod_arr_data_con = data_con })
505        = return . wrapFamInstBody tycon tys
506                 . mkConApp data_con
507                 $ map Type tys ++ map Var (len_var : repr_vars)
508
509     to_prod repr_vars@(r : _)
510             (ProdRepr { prod_components   = tys
511                       , prod_arr_tycon    = tycon
512                       , prod_arr_data_con = data_con })
513       = do
514           len <- lengthPA (Var r)
515           return . wrapFamInstBody tycon tys
516                  . mkConApp data_con
517                  $ map Type tys ++ len : map Var repr_vars
518
519     to_prod [var] (IdRepr ty)   = return (Var var)
520     to_prod [var] (VoidRepr {}) = return (Var var)
521
522
523 buildFromArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
524 buildFromArrPRepr repr vect_tc prepr_tc arr_tc
525   = do
526       arg_ty     <- mkPArrayType =<< mkPReprType el_ty
527       arg        <- newLocalVar FSLIT("xs") arg_ty
528
529       res_ty     <- mkPArrayType el_ty
530
531       shape_vars <- arrShapeVars repr
532       repr_vars  <- arrReprVars  repr
533
534       parray_co  <- mkBuiltinCo parrayTyCon
535
536       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
537           co           = mkAppCoercion parray_co
538                        $ mkTyConApp repr_co var_tys
539
540           scrut  = mkCoerce co (Var arg)
541
542           result = wrapFamInstBody arr_tc var_tys
543                  . mkConApp arr_dc
544                  $ map Type var_tys ++ map Var (shape_vars ++ concat repr_vars)
545
546       liftM (Lam arg)
547             (from_repr repr scrut shape_vars repr_vars res_ty result)
548   where
549     var_tys = mkTyVarTys $ tyConTyVars vect_tc
550     el_ty   = mkTyConApp vect_tc var_tys
551
552     [arr_dc] = tyConDataCons arr_tc
553
554     from_repr (SumRepr { sum_components   = prods
555                        , sum_arr_tycon    = tycon
556                        , sum_arr_data_con = data_con })
557               expr
558               shape_vars
559               repr_vars
560               res_ty
561               body
562       = do
563           vars <- mapM (newLocalVar FSLIT("xs")) =<< mapM arrReprType prods
564           result <- go prods repr_vars vars body
565
566           let scrut = unwrapFamInstScrut tycon ty_args expr
567           return . Case scrut (mkWildId scrut_ty) res_ty
568                  $ [(DataAlt data_con, shape_vars ++ vars, result)]
569       where
570         ty_args  = map reprType prods
571         scrut_ty = mkTyConApp tycon ty_args
572
573         go [] [] [] body = return body
574         go (prod : prods) (repr_vars : rss) (var : vars) body
575           = do
576               shape_vars <- mapM (newLocalVar FSLIT("s")) =<< arrShapeTys prod
577
578               from_prod prod (Var var) shape_vars repr_vars res_ty
579                 =<< go prods rss vars body
580
581     from_repr repr expr shape_vars [repr_vars] res_ty body
582       = from_prod repr expr shape_vars repr_vars res_ty body
583
584     from_prod prod@(ProdRepr { prod_components = tys
585                              , prod_arr_tycon  = tycon
586                              , prod_arr_data_con = data_con })
587               expr
588               shape_vars
589               repr_vars
590               res_ty
591               body
592       = do
593           let scrut    = unwrapFamInstScrut tycon tys expr
594               scrut_ty = mkTyConApp tycon tys
595           ty <- arrReprType prod
596
597           return $ Case scrut (mkWildId scrut_ty) res_ty
598                    [(DataAlt data_con, shape_vars ++ repr_vars, body)]
599
600     from_prod (IdRepr ty)
601               expr
602               shape_vars
603               [repr_var]
604               res_ty
605               body
606       = return $ Let (NonRec repr_var expr) body
607
608     from_prod (VoidRepr {})
609               expr
610               shape_vars
611               [repr_var]
612               res_ty
613               body
614       = return $ Let (NonRec repr_var expr) body
615
616 buildPRDictRepr :: Repr -> VM CoreExpr
617 buildPRDictRepr (VoidRepr { void_tycon = tycon })
618   = prDFunOfTyCon tycon
619 buildPRDictRepr (IdRepr ty) = mkPR ty
620 buildPRDictRepr (ProdRepr {
621                    prod_components = tys
622                  , prod_tycon      = tycon
623                  })
624   = do
625       prs  <- mapM mkPR tys
626       dfun <- prDFunOfTyCon tycon
627       return $ dfun `mkTyApps` tys `mkApps` prs
628
629 buildPRDictRepr (SumRepr {
630                    sum_components = prods
631                  , sum_tycon      = tycon })
632   = do
633       prs  <- mapM buildPRDictRepr prods
634       dfun <- prDFunOfTyCon tycon
635       return $ dfun `mkTyApps` map reprType prods `mkApps` prs
636
637 buildPRDict :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
638 buildPRDict repr vect_tc prepr_tc _
639   = do
640       dict  <- buildPRDictRepr repr
641
642       pr_co <- mkBuiltinCo prTyCon
643       let co = mkAppCoercion pr_co
644              . mkSymCoercion
645              $ mkTyConApp arg_co var_tys
646
647       return $ mkCoerce co dict
648   where
649     var_tys = mkTyVarTys $ tyConTyVars vect_tc
650
651     Just arg_co = tyConFamilyCoercion_maybe prepr_tc
652
653 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
654 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
655   do
656     name'  <- cloneName mkPArrayTyConOcc orig_name
657     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
658     parray <- builtin parrayTyCon
659
660     liftDs $ buildAlgTyCon name'
661                            tyvars
662                            []          -- no stupid theta
663                            rhs
664                            rec_flag    -- FIXME: is this ok?
665                            False       -- FIXME: no generics
666                            False       -- not GADT syntax
667                            (Just $ mk_fam_inst parray vect_tc)
668   where
669     orig_name = tyConName orig_tc
670     tyvars = tyConTyVars vect_tc
671     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
672
673
674 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
675 buildPArrayTyConRhs orig_name vect_tc repr_tc
676   = do
677       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
678       return $ DataTyCon { data_cons = [data_con], is_enum = False }
679
680 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
681 buildPArrayDataCon orig_name vect_tc repr_tc
682   = do
683       dc_name  <- cloneName mkPArrayDataConOcc orig_name
684       repr     <- mkRepr vect_tc
685
686       shape_tys <- arrShapeTys repr
687       repr_tys  <- arrReprTys  repr
688
689       let tys = shape_tys ++ concat repr_tys
690
691       liftDs $ buildDataCon dc_name
692                             False                  -- not infix
693                             (map (const NotMarkedStrict) tys)
694                             []                     -- no field labels
695                             (tyConTyVars vect_tc)
696                             []                     -- no existentials
697                             []                     -- no eq spec
698                             []                     -- no context
699                             tys
700                             repr_tc
701
702 mkPADFun :: TyCon -> VM Var
703 mkPADFun vect_tc
704   = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
705
706 buildTyConBindings :: TyCon -> TyCon -> TyCon -> TyCon -> Var
707                    -> VM [(Var, CoreExpr)]
708 buildTyConBindings orig_tc vect_tc prepr_tc arr_tc dfun
709   = do
710       repr  <- mkRepr vect_tc
711       vectDataConWorkers repr orig_tc vect_tc arr_tc
712       dict <- buildPADict repr vect_tc prepr_tc arr_tc dfun
713       binds <- takeHoisted
714       return $ (dfun, dict) : binds
715   where
716     orig_dcs = tyConDataCons orig_tc
717     vect_dcs = tyConDataCons vect_tc
718     [arr_dc] = tyConDataCons arr_tc
719
720     repr_tys = map dataConRepArgTys vect_dcs
721
722 vectDataConWorkers :: Repr -> TyCon -> TyCon -> TyCon
723                    -> VM ()
724 vectDataConWorkers repr orig_tc vect_tc arr_tc
725   = do
726       arr_tys <- arrReprElemTys repr
727       bs <- sequence
728           . zipWith3 def_worker  (tyConDataCons orig_tc) rep_tys
729           $ zipWith4 mk_data_con (tyConDataCons vect_tc)
730                                  rep_tys
731                                  (inits arr_tys)
732                                  (tail $ tails arr_tys)
733       mapM_ (uncurry hoistBinding) bs
734   where
735     tyvars   = tyConTyVars vect_tc
736     var_tys  = mkTyVarTys tyvars
737     ty_args  = map Type var_tys
738
739     res_ty   = mkTyConApp vect_tc var_tys
740
741     rep_tys  = map dataConRepArgTys $ tyConDataCons vect_tc
742
743     [arr_dc] = tyConDataCons arr_tc
744
745     mk_data_con con tys pre post
746       = liftM2 (,) (vect_data_con con)
747                    (lift_data_con tys (concat pre)
748                                       (concat post)
749                                       (mkDataConTag con))
750
751     vect_data_con con = return $ mkConApp con ty_args
752     lift_data_con tys pre_tys post_tys tag
753       = do
754           len  <- builtin liftingContext
755           args <- mapM (newLocalVar FSLIT("xs"))
756                   =<< mapM mkPArrayType tys
757
758           shape <- replicateShape repr (Var len) tag
759           repr  <- mk_arr_repr (Var len) (map Var args)
760
761           pre   <- mapM emptyPA pre_tys
762           post  <- mapM emptyPA post_tys
763
764           return . mkLams (len : args)
765                  . wrapFamInstBody arr_tc var_tys
766                  . mkConApp arr_dc
767                  $ ty_args ++ shape ++ pre ++ repr ++ post
768
769     mk_arr_repr len []
770       = do
771           units <- replicatePA len (Var unitDataConId)
772           return [units]
773
774     mk_arr_repr len arrs = return arrs
775
776     def_worker data_con arg_tys mk_body
777       = do
778           body <- closedV
779                 . inBind orig_worker
780                 . polyAbstract tyvars $ \abstract ->
781                   liftM (abstract . vectorised)
782                 $ buildClosures tyvars [] arg_tys res_ty mk_body
783
784           vect_worker <- cloneId mkVectOcc orig_worker (exprType body)
785           defGlobalVar orig_worker vect_worker
786           return (vect_worker, body)
787       where
788         orig_worker = dataConWorkId data_con
789
790 buildPADict :: Repr -> TyCon -> TyCon -> TyCon -> Var -> VM CoreExpr
791 buildPADict repr vect_tc prepr_tc arr_tc dfun
792   = polyAbstract tvs $ \abstract ->
793     do
794       meth_binds <- mapM (mk_method repr) paMethods
795       let meth_exprs = map (Var . fst) meth_binds
796
797       pa_dc <- builtin paDataCon
798       let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
799           body = Let (Rec meth_binds) dict
800       return . mkInlineMe $ abstract body
801   where
802     tvs = tyConTyVars arr_tc
803     arg_tys = mkTyVarTys tvs
804
805     mk_method repr (name, build)
806       = localV
807       $ do
808           body <- build repr vect_tc prepr_tc arr_tc
809           var  <- newLocalVar name (exprType body)
810           return (var, mkInlineMe body)
811
812 paMethods = [(FSLIT("toPRepr"),      buildToPRepr),
813              (FSLIT("fromPRepr"),    buildFromPRepr),
814              (FSLIT("toArrPRepr"),   buildToArrPRepr),
815              (FSLIT("fromArrPRepr"), buildFromArrPRepr),
816              (FSLIT("dictPRepr"),    buildPRDict)]
817
818 -- | Split the given tycons into two sets depending on whether they have to be
819 -- converted (first list) or not (second list). The first argument contains
820 -- information about the conversion status of external tycons:
821 --
822 --   * tycons which have converted versions are mapped to True
823 --   * tycons which are not changed by vectorisation are mapped to False
824 --   * tycons which can't be converted are not elements of the map
825 --
826 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
827 classifyTyCons = classify [] []
828   where
829     classify conv keep cs [] = (conv, keep)
830     classify conv keep cs ((tcs, ds) : rs)
831       | can_convert && must_convert
832         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
833       | can_convert
834         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
835       | otherwise
836         = classify conv keep cs rs
837       where
838         refs = ds `delListFromUniqSet` tcs
839
840         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
841         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
842
843         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
844
845 -- | Compute mutually recursive groups of tycons in topological order
846 --
847 tyConGroups :: [TyCon] -> [TyConGroup]
848 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
849   where
850     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
851                                 , let ds = tyConsOfTyCon tc]
852
853     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
854     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
855       where
856         (tcs, dss) = unzip els
857
858 tyConsOfTyCon :: TyCon -> UniqSet TyCon
859 tyConsOfTyCon
860   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
861
862 tyConsOfType :: Type -> UniqSet TyCon
863 tyConsOfType ty
864   | Just ty' <- coreView ty    = tyConsOfType ty'
865 tyConsOfType (TyVarTy v)       = emptyUniqSet
866 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
867   where
868     extend | isUnLiftedTyCon tc
869            || isTupleTyCon   tc = id
870
871            | otherwise          = (`addOneToUniqSet` tc)
872
873 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
874 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
875                                  `addOneToUniqSet` funTyCon
876 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
877 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
878
879 tyConsOfTypes :: [Type] -> UniqSet TyCon
880 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
881