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