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