1 module VectType ( vectTyCon, vectType, vectTypeEnv,
2 PAInstance, buildPADict )
5 #include "HsVersions.h"
11 import HscTypes ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
20 import FamInstEnv ( FamInst, mkLocalFamInst )
21 import InstEnv ( Instance, mkLocalInstance, instanceDFunId )
24 import BasicTypes ( StrictnessMark(..), OverlapFlag(..), boolToRecFlag )
26 import Id ( mkWildId )
27 import Name ( Name, getOccName )
29 import TysWiredIn ( unitTy, intTy, intDataCon )
30 import TysPrim ( intPrimTy )
35 import Digraph ( SCC(..), stronglyConnComp )
39 import Control.Monad ( liftM, liftM2, zipWithM, zipWithM_ )
40 import Data.List ( inits, tails, zipWith4, zipWith5 )
42 -- ----------------------------------------------------------------------------
45 vectTyCon :: TyCon -> VM TyCon
47 | isFunTyCon tc = builtin closureTyCon
48 | isBoxedTupleTyCon tc = return tc
49 | isUnLiftedTyCon tc = return tc
53 Just tc' -> return tc'
55 -- FIXME: just for now
56 Nothing -> pprTrace "ccTyCon:" (ppr tc) $ return tc
58 vectType :: Type -> VM Type
59 vectType ty | Just ty' <- coreView ty = vectType ty'
60 vectType (TyVarTy tv) = return $ TyVarTy tv
61 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
62 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
63 vectType (FunTy ty1 ty2) = liftM2 TyConApp (builtin closureTyCon)
64 (mapM vectType [ty1,ty2])
65 vectType ty@(ForAllTy _ _)
67 mdicts <- mapM paDictArgType tyvars
68 mono_ty' <- vectType mono_ty
69 return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
71 (tyvars, mono_ty) = splitForAllTys ty
73 vectType ty = pprPanic "vectType:" (ppr ty)
75 -- ----------------------------------------------------------------------------
78 type TyConGroup = ([TyCon], UniqSet TyCon)
80 data PAInstance = PAInstance {
82 , painstOrigTyCon :: TyCon
83 , painstVectTyCon :: TyCon
84 , painstArrTyCon :: TyCon
87 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [(Var, CoreExpr)])
90 cs <- readGEnv $ mk_map . global_tycons
91 let (conv_tcs, keep_tcs) = classifyTyCons cs groups
92 keep_dcs = concatMap tyConDataCons keep_tcs
93 zipWithM_ defTyCon keep_tcs keep_tcs
94 zipWithM_ defDataCon keep_dcs keep_dcs
95 new_tcs <- vectTyConDecls conv_tcs
97 let orig_tcs = keep_tcs ++ conv_tcs
98 vect_tcs = keep_tcs ++ new_tcs
100 repr_tcs <- zipWithM buildPReprTyCon orig_tcs vect_tcs
101 parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
102 dfuns <- mapM mkPADFun vect_tcs
103 defTyConPAs (zip vect_tcs dfuns)
104 binds <- sequence (zipWith5 buildTyConBindings orig_tcs
110 let all_new_tcs = new_tcs ++ repr_tcs ++ parr_tcs
112 let new_env = extendTypeEnvList env
113 (map ATyCon all_new_tcs
114 ++ [ADataCon dc | tc <- all_new_tcs
115 , dc <- tyConDataCons tc])
117 return (new_env, map mkLocalFamInst (repr_tcs ++ parr_tcs), concat binds)
119 tycons = typeEnvTyCons env
120 groups = tyConGroups tycons
122 mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
124 keep_tc tc = let dcs = tyConDataCons tc
126 defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
129 vectTyConDecls :: [TyCon] -> VM [TyCon]
130 vectTyConDecls tcs = fixV $ \tcs' ->
132 mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
133 mapM vectTyConDecl tcs
136 lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
138 vectTyConDecl :: TyCon -> VM TyCon
141 name' <- cloneName mkVectTyConOcc name
142 rhs' <- vectAlgTyConRhs (algTyConRhs tc)
144 liftDs $ buildAlgTyCon name'
146 [] -- no stupid theta
148 rec_flag -- FIXME: is this ok?
149 False -- FIXME: no generics
150 False -- not GADT syntax
151 Nothing -- not a family instance
154 tyvars = tyConTyVars tc
155 rec_flag = boolToRecFlag (isRecursiveTyCon tc)
157 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
158 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
162 data_cons' <- mapM vectDataCon data_cons
163 zipWithM_ defDataCon data_cons data_cons'
164 return $ DataTyCon { data_cons = data_cons'
168 vectDataCon :: DataCon -> VM DataCon
170 | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
171 | not . null $ dataConEqSpec dc = pprPanic "vectDataCon: eq spec" (ppr dc)
174 name' <- cloneName mkVectDataConOcc name
175 tycon' <- vectTyCon tycon
176 arg_tys <- mapM vectType rep_arg_tys
178 liftDs $ buildDataCon name'
180 (map (const NotMarkedStrict) arg_tys)
181 [] -- no labelled fields
183 [] -- no existential tvs for now
184 [] -- no eq spec for now
189 name = dataConName dc
190 univ_tvs = dataConUnivTyVars dc
191 rep_arg_tys = dataConRepArgTys dc
192 tycon = dataConTyCon dc
194 mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
195 mk_fam_inst fam_tc arg_tc
196 = (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
198 buildPReprTyCon :: TyCon -> TyCon -> VM TyCon
199 buildPReprTyCon orig_tc vect_tc
201 name <- cloneName mkPReprTyConOcc (tyConName orig_tc)
202 rhs_ty <- buildPReprType vect_tc
203 prepr_tc <- builtin preprTyCon
204 liftDs $ buildSynTyCon name
206 (SynonymTyCon rhs_ty)
207 (Just $ mk_fam_inst prepr_tc vect_tc)
209 tyvars = tyConTyVars vect_tc
211 buildPReprType :: TyCon -> VM Type
212 buildPReprType = mkPReprType . map dataConRepArgTys . tyConDataCons
214 buildToPRepr :: Shape -> TyCon -> TyCon -> TyCon -> VM CoreExpr
215 buildToPRepr _ vect_tc prepr_tc _
217 arg <- newLocalVar FSLIT("x") arg_ty
218 bndrss <- mapM (mapM (newLocalVar FSLIT("x"))) rep_tys
219 (alt_bodies, res_ty) <- mkPReprAlts $ map (map Var) bndrss
222 . wrapFamInstBody prepr_tc var_tys
223 . Case (Var arg) (mkWildId arg_ty) res_ty
224 $ zipWith3 mk_alt data_cons bndrss alt_bodies
226 var_tys = mkTyVarTys $ tyConTyVars vect_tc
227 arg_ty = mkTyConApp vect_tc var_tys
228 data_cons = tyConDataCons vect_tc
229 rep_tys = map dataConRepArgTys data_cons
231 mk_alt data_con bndrs body = (DataAlt data_con, bndrs, body)
233 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
234 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
236 name' <- cloneName mkPArrayTyConOcc orig_name
237 rhs <- buildPArrayTyConRhs orig_name vect_tc repr_tc
238 parray <- builtin parrayTyCon
240 liftDs $ buildAlgTyCon name'
242 [] -- no stupid theta
244 rec_flag -- FIXME: is this ok?
245 False -- FIXME: no generics
246 False -- not GADT syntax
247 (Just $ mk_fam_inst parray vect_tc)
249 orig_name = tyConName orig_tc
250 tyvars = tyConTyVars vect_tc
251 rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
254 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
255 buildPArrayTyConRhs orig_name vect_tc repr_tc
257 data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
258 return $ DataTyCon { data_cons = [data_con], is_enum = False }
260 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
261 buildPArrayDataCon orig_name vect_tc repr_tc
263 dc_name <- cloneName mkPArrayDataConOcc orig_name
264 shape <- tyConShape vect_tc
265 repr_tys <- mapM mkPArrayType types
267 liftDs $ buildDataCon dc_name
269 (shapeStrictness shape ++ map (const NotMarkedStrict) repr_tys)
270 [] -- no field labels
271 (tyConTyVars vect_tc)
272 [] -- no existentials
275 (shapeReprTys shape ++ repr_tys)
278 types = [ty | dc <- tyConDataCons vect_tc
279 , ty <- dataConRepArgTys dc]
281 mkPADFun :: TyCon -> VM Var
283 = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
286 shapeReprTys :: [Type]
287 , shapeStrictness :: [StrictnessMark]
288 , shapeLength :: [CoreExpr] -> VM CoreExpr
289 , shapeReplicate :: CoreExpr -> CoreExpr -> VM [CoreExpr]
292 tyConShape :: TyCon -> VM Shape
294 | isProductTyCon vect_tc
296 shapeReprTys = [intPrimTy]
297 , shapeStrictness = [NotMarkedStrict]
298 , shapeLength = \[len] -> return len
299 , shapeReplicate = \len _ -> return [len]
304 repr_ty <- mkPArrayType intTy -- FIXME: we want to unbox this
306 shapeReprTys = [repr_ty]
307 , shapeStrictness = [MarkedStrict]
308 , shapeLength = \[sel] -> lengthPA sel
309 , shapeReplicate = \len n -> do
310 e <- replicatePA len n
314 buildTyConBindings :: TyCon -> TyCon -> TyCon -> TyCon -> Var
315 -> VM [(Var, CoreExpr)]
316 buildTyConBindings orig_tc vect_tc prepr_tc arr_tc dfun
318 shape <- tyConShape vect_tc
319 sequence_ (zipWith4 (vectDataConWorker shape vect_tc arr_tc arr_dc)
324 dict <- buildPADict shape vect_tc prepr_tc arr_tc dfun
326 return $ (dfun, dict) : binds
328 orig_dcs = tyConDataCons orig_tc
329 vect_dcs = tyConDataCons vect_tc
330 [arr_dc] = tyConDataCons arr_tc
332 repr_tys = map dataConRepArgTys vect_dcs
334 vectDataConWorker :: Shape -> TyCon -> TyCon -> DataCon
335 -> DataCon -> DataCon -> [[Type]] -> [[Type]]
337 vectDataConWorker shape vect_tc arr_tc arr_dc orig_dc vect_dc pre (dc_tys : post)
341 . polyAbstract tvs $ \abstract ->
342 liftM (abstract . vectorised)
343 $ buildClosures tvs [] dc_tys res_ty (liftM2 (,) mk_vect mk_lift)
345 worker <- cloneId mkVectOcc orig_worker (exprType clo)
346 hoistBinding worker clo
347 defGlobalVar orig_worker worker
350 tvs = tyConTyVars vect_tc
351 arg_tys = mkTyVarTys tvs
352 res_ty = mkTyConApp vect_tc arg_tys
354 orig_worker = dataConWorkId orig_dc
356 mk_vect = return . mkConApp vect_dc $ map Type arg_tys
358 len <- newLocalVar FSLIT("n") intPrimTy
359 arr_tys <- mapM mkPArrayType dc_tys
360 args <- mapM (newLocalVar FSLIT("xs")) arr_tys
361 shapes <- shapeReplicate shape
363 (mkDataConTag vect_dc)
365 empty_pre <- mapM emptyPA (concat pre)
366 empty_post <- mapM emptyPA (concat post)
368 return . mkLams (len : args)
369 . wrapFamInstBody arr_tc arg_tys
371 $ map Type arg_tys ++ shapes
376 buildPADict :: Shape -> TyCon -> TyCon -> TyCon -> Var -> VM CoreExpr
377 buildPADict shape vect_tc prepr_tc arr_tc dfun
378 = polyAbstract tvs $ \abstract ->
380 meth_binds <- mapM (mk_method shape) paMethods
381 let meth_exprs = map (Var . fst) meth_binds
383 pa_dc <- builtin paDataCon
384 let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
385 body = Let (Rec meth_binds) dict
386 return . mkInlineMe $ abstract body
388 tvs = tyConTyVars arr_tc
389 arg_tys = mkTyVarTys tvs
391 mk_method shape (name, build)
394 body <- build shape vect_tc prepr_tc arr_tc
395 var <- newLocalVar name (exprType body)
396 return (var, mkInlineMe body)
398 paMethods = [(FSLIT("lengthPA"), buildLengthPA),
399 (FSLIT("replicatePA"), buildReplicatePA),
400 (FSLIT("toPRepr"), buildToPRepr)]
402 buildLengthPA :: Shape -> TyCon -> TyCon -> TyCon -> VM CoreExpr
403 buildLengthPA shape vect_tc _ arr_tc
405 parr_ty <- mkPArrayType (mkTyConApp vect_tc arg_tys)
406 arg <- newLocalVar FSLIT("xs") parr_ty
407 shapes <- mapM (newLocalVar FSLIT("sh")) shape_tys
408 wilds <- mapM newDummyVar repr_tys
409 let scrut = unwrapFamInstScrut arr_tc arg_tys (Var arg)
410 scrut_ty = exprType scrut
412 body <- shapeLength shape (map Var shapes)
415 $ Case scrut (mkWildId scrut_ty) intPrimTy
416 [(DataAlt repr_dc, shapes ++ wilds, body)]
418 arg_tys = mkTyVarTys $ tyConTyVars arr_tc
419 [repr_dc] = tyConDataCons arr_tc
421 shape_tys = shapeReprTys shape
422 repr_tys = drop (length shape_tys) (dataConRepArgTys repr_dc)
424 -- data T = C0 t1 ... tm
428 -- data [:T:] = A ![:Int:] [:t1:] ... [:un:]
430 -- replicatePA :: Int# -> T -> [:T:]
432 -- = let c = case t of
438 -- C0 x1 _ ... _ -> replicatePA @t1 n# x1
444 -- Ck _ ... _ yn -> replicatePA @un n# yn
447 -- A (replicatePA @Int n# c) xs1 ... ysn
451 buildReplicatePA :: Shape -> TyCon -> TyCon -> TyCon -> VM CoreExpr
452 buildReplicatePA shape vect_tc _ arr_tc
454 len_var <- newLocalVar FSLIT("n") intPrimTy
455 val_var <- newLocalVar FSLIT("x") val_ty
457 let len = Var len_var
460 shape_reprs <- shapeReplicate shape len (ctr_num val)
461 reprs <- liftM concat $ mapM (mk_comp_arrs len val) vect_dcs
463 return . mkLams [len_var, val_var]
464 . wrapFamInstBody arr_tc arg_tys
465 $ mkConApp arr_dc (map Type arg_tys ++ shape_reprs ++ reprs)
467 arg_tys = mkTyVarTys (tyConTyVars arr_tc)
468 val_ty = mkTyConApp vect_tc arg_tys
469 wild = mkWildId val_ty
470 vect_dcs = tyConDataCons vect_tc
471 [arr_dc] = tyConDataCons arr_tc
473 ctr_num val = Case val wild intTy (zipWith ctr_num_alt vect_dcs [0..])
474 ctr_num_alt dc i = (DataAlt dc, map mkWildId (dataConRepArgTys dc),
475 mkConApp intDataCon [mkIntLitInt i])
478 mk_comp_arrs len val dc = let tys = dataConRepArgTys dc
479 wilds = map mkWildId tys
481 sequence (zipWith3 (mk_comp_arr len val dc)
482 tys (inits wilds) (tails wilds))
484 mk_comp_arr len val dc ty pre (_:post)
486 var <- newLocalVar FSLIT("x") ty
487 rep <- replicatePA len (Var var)
489 arr_ty <- mkPArrayType ty
491 return $ Case val wild arr_ty
492 [(DEFAULT, [], empty), (DataAlt dc, pre ++ (var : post), rep)]
494 -- | Split the given tycons into two sets depending on whether they have to be
495 -- converted (first list) or not (second list). The first argument contains
496 -- information about the conversion status of external tycons:
498 -- * tycons which have converted versions are mapped to True
499 -- * tycons which are not changed by vectorisation are mapped to False
500 -- * tycons which can't be converted are not elements of the map
502 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
503 classifyTyCons = classify [] []
505 classify conv keep cs [] = (conv, keep)
506 classify conv keep cs ((tcs, ds) : rs)
507 | can_convert && must_convert
508 = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
510 = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
512 = classify conv keep cs rs
514 refs = ds `delListFromUniqSet` tcs
516 can_convert = isNullUFM (refs `minusUFM` cs) && all convertable tcs
517 must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
519 convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
521 -- | Compute mutually recursive groups of tycons in topological order
523 tyConGroups :: [TyCon] -> [TyConGroup]
524 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
526 edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
527 , let ds = tyConsOfTyCon tc]
529 mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
530 mk_grp (CyclicSCC els) = (tcs, unionManyUniqSets dss)
532 (tcs, dss) = unzip els
534 tyConsOfTyCon :: TyCon -> UniqSet TyCon
536 = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
538 tyConsOfType :: Type -> UniqSet TyCon
540 | Just ty' <- coreView ty = tyConsOfType ty'
541 tyConsOfType (TyVarTy v) = emptyUniqSet
542 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
544 extend | isUnLiftedTyCon tc
545 || isTupleTyCon tc = id
547 | otherwise = (`addOneToUniqSet` tc)
549 tyConsOfType (AppTy a b) = tyConsOfType a `unionUniqSets` tyConsOfType b
550 tyConsOfType (FunTy a b) = (tyConsOfType a `unionUniqSets` tyConsOfType b)
551 `addOneToUniqSet` funTyCon
552 tyConsOfType (ForAllTy _ ty) = tyConsOfType ty
553 tyConsOfType other = pprPanic "ClosureConv.tyConsOfType" $ ppr other
555 tyConsOfTypes :: [Type] -> UniqSet TyCon
556 tyConsOfTypes = unionManyUniqSets . map tyConsOfType