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