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