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