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 )
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 (zipWith4 buildTyConBindings orig_tcs vect_tcs parr_tcs dfuns)
106 let all_new_tcs = new_tcs ++ repr_tcs ++ parr_tcs
108 let new_env = extendTypeEnvList env
109 (map ATyCon all_new_tcs
110 ++ [ADataCon dc | tc <- all_new_tcs
111 , dc <- tyConDataCons tc])
113 return (new_env, map mkLocalFamInst (repr_tcs ++ parr_tcs), concat binds)
115 tycons = typeEnvTyCons env
116 groups = tyConGroups tycons
118 mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
120 keep_tc tc = let dcs = tyConDataCons tc
122 defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
125 vectTyConDecls :: [TyCon] -> VM [TyCon]
126 vectTyConDecls tcs = fixV $ \tcs' ->
128 mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
129 mapM vectTyConDecl tcs
132 lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
134 vectTyConDecl :: TyCon -> VM TyCon
137 name' <- cloneName mkVectTyConOcc name
138 rhs' <- vectAlgTyConRhs (algTyConRhs tc)
140 liftDs $ buildAlgTyCon name'
142 [] -- no stupid theta
144 rec_flag -- FIXME: is this ok?
145 False -- FIXME: no generics
146 False -- not GADT syntax
147 Nothing -- not a family instance
150 tyvars = tyConTyVars tc
151 rec_flag = boolToRecFlag (isRecursiveTyCon tc)
153 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
154 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
158 data_cons' <- mapM vectDataCon data_cons
159 zipWithM_ defDataCon data_cons data_cons'
160 return $ DataTyCon { data_cons = data_cons'
164 vectDataCon :: DataCon -> VM DataCon
166 | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
167 | not . null $ dataConEqSpec dc = pprPanic "vectDataCon: eq spec" (ppr dc)
170 name' <- cloneName mkVectDataConOcc name
171 tycon' <- vectTyCon tycon
172 arg_tys <- mapM vectType rep_arg_tys
174 liftDs $ buildDataCon name'
176 (map (const NotMarkedStrict) arg_tys)
177 [] -- no labelled fields
179 [] -- no existential tvs for now
180 [] -- no eq spec for now
185 name = dataConName dc
186 univ_tvs = dataConUnivTyVars dc
187 rep_arg_tys = dataConRepArgTys dc
188 tycon = dataConTyCon dc
190 mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
191 mk_fam_inst fam_tc arg_tc
192 = (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
194 mkSumOfProdRepr :: [[Type]] -> VM Type
195 mkSumOfProdRepr [] = panic "mkSumOfProdRepr"
198 embed <- builtin embedTyCon
199 plus <- builtin plusTyCon
200 cross <- builtin crossTyCon
202 return . foldr1 (mk_bin plus)
204 . map (map (mk_un embed))
207 mkprod cross [] = unitTy
208 mkprod cross tys = foldr1 (mk_bin cross) tys
210 mk_un tc ty = mkTyConApp tc [ty]
211 mk_bin tc ty1 ty2 = mkTyConApp tc [ty1,ty2]
213 buildPReprTyCon :: TyCon -> TyCon -> VM TyCon
214 buildPReprTyCon orig_tc vect_tc
216 name <- cloneName mkPReprTyConOcc (tyConName orig_tc)
217 rhs_ty <- buildPReprRhsTy vect_tc
218 prepr_tc <- builtin preprTyCon
219 liftDs $ buildSynTyCon name
221 (SynonymTyCon rhs_ty)
222 (Just $ mk_fam_inst prepr_tc vect_tc)
224 tyvars = tyConTyVars vect_tc
226 buildPReprRhsTy :: TyCon -> VM Type
227 buildPReprRhsTy = mkSumOfProdRepr . map dataConRepArgTys . tyConDataCons
229 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
230 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
232 name' <- cloneName mkPArrayTyConOcc orig_name
233 rhs <- buildPArrayTyConRhs orig_name vect_tc repr_tc
234 parray <- builtin parrayTyCon
236 liftDs $ buildAlgTyCon name'
238 [] -- no stupid theta
240 rec_flag -- FIXME: is this ok?
241 False -- FIXME: no generics
242 False -- not GADT syntax
243 (Just $ mk_fam_inst parray vect_tc)
245 orig_name = tyConName orig_tc
246 tyvars = tyConTyVars vect_tc
247 rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
250 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
251 buildPArrayTyConRhs orig_name vect_tc repr_tc
253 data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
254 return $ DataTyCon { data_cons = [data_con], is_enum = False }
256 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
257 buildPArrayDataCon orig_name vect_tc repr_tc
259 dc_name <- cloneName mkPArrayDataConOcc orig_name
260 shape <- tyConShape vect_tc
261 repr_tys <- mapM mkPArrayType types
263 liftDs $ buildDataCon dc_name
265 (shapeStrictness shape ++ map (const NotMarkedStrict) repr_tys)
266 [] -- no field labels
267 (tyConTyVars vect_tc)
268 [] -- no existentials
271 (shapeReprTys shape ++ repr_tys)
274 types = [ty | dc <- tyConDataCons vect_tc
275 , ty <- dataConRepArgTys dc]
277 mkPADFun :: TyCon -> VM Var
279 = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
282 shapeReprTys :: [Type]
283 , shapeStrictness :: [StrictnessMark]
284 , shapeLength :: [CoreExpr] -> VM CoreExpr
285 , shapeReplicate :: CoreExpr -> CoreExpr -> VM [CoreExpr]
288 tyConShape :: TyCon -> VM Shape
290 | isProductTyCon vect_tc
292 shapeReprTys = [intPrimTy]
293 , shapeStrictness = [NotMarkedStrict]
294 , shapeLength = \[len] -> return len
295 , shapeReplicate = \len _ -> return [len]
300 repr_ty <- mkPArrayType intTy -- FIXME: we want to unbox this
302 shapeReprTys = [repr_ty]
303 , shapeStrictness = [MarkedStrict]
304 , shapeLength = \[sel] -> lengthPA sel
305 , shapeReplicate = \len n -> do
306 e <- replicatePA len n
310 buildTyConBindings :: TyCon -> TyCon -> TyCon -> Var -> VM [(Var, CoreExpr)]
311 buildTyConBindings orig_tc vect_tc arr_tc dfun
313 shape <- tyConShape vect_tc
314 sequence_ (zipWith4 (vectDataConWorker shape vect_tc arr_tc arr_dc)
319 dict <- buildPADict shape vect_tc arr_tc dfun
321 return $ (dfun, dict) : binds
323 orig_dcs = tyConDataCons orig_tc
324 vect_dcs = tyConDataCons vect_tc
325 [arr_dc] = tyConDataCons arr_tc
327 repr_tys = map dataConRepArgTys vect_dcs
329 vectDataConWorker :: Shape -> TyCon -> TyCon -> DataCon
330 -> DataCon -> DataCon -> [[Type]] -> [[Type]]
332 vectDataConWorker shape vect_tc arr_tc arr_dc orig_dc vect_dc pre (dc_tys : post)
336 . polyAbstract tvs $ \abstract ->
337 liftM (abstract . vectorised)
338 $ buildClosures tvs [] dc_tys res_ty (liftM2 (,) mk_vect mk_lift)
340 worker <- cloneId mkVectOcc orig_worker (exprType clo)
341 hoistBinding worker clo
342 defGlobalVar orig_worker worker
345 tvs = tyConTyVars vect_tc
346 arg_tys = mkTyVarTys tvs
347 res_ty = mkTyConApp vect_tc arg_tys
349 orig_worker = dataConWorkId orig_dc
351 mk_vect = return . mkConApp vect_dc $ map Type arg_tys
353 len <- newLocalVar FSLIT("n") intPrimTy
354 arr_tys <- mapM mkPArrayType dc_tys
355 args <- mapM (newLocalVar FSLIT("xs")) arr_tys
356 shapes <- shapeReplicate shape
358 (mkDataConTag vect_dc)
360 empty_pre <- mapM emptyPA (concat pre)
361 empty_post <- mapM emptyPA (concat post)
363 return . mkLams (len : args)
364 . wrapFamInstBody arr_tc arg_tys
366 $ map Type arg_tys ++ shapes
371 buildPADict :: Shape -> TyCon -> TyCon -> Var -> VM CoreExpr
372 buildPADict shape vect_tc arr_tc dfun
373 = polyAbstract tvs $ \abstract ->
375 meth_binds <- mapM (mk_method shape) paMethods
376 let meth_exprs = map (Var . fst) meth_binds
378 pa_dc <- builtin paDataCon
379 let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
380 body = Let (Rec meth_binds) dict
381 return . mkInlineMe $ abstract body
383 tvs = tyConTyVars arr_tc
384 arg_tys = mkTyVarTys tvs
386 mk_method shape (name, build)
389 body <- build shape vect_tc arr_tc
390 var <- newLocalVar name (exprType body)
391 return (var, mkInlineMe body)
393 paMethods = [(FSLIT("lengthPA"), buildLengthPA),
394 (FSLIT("replicatePA"), buildReplicatePA)]
396 buildLengthPA :: Shape -> TyCon -> TyCon -> VM CoreExpr
397 buildLengthPA shape vect_tc arr_tc
399 parr_ty <- mkPArrayType (mkTyConApp vect_tc arg_tys)
400 arg <- newLocalVar FSLIT("xs") parr_ty
401 shapes <- mapM (newLocalVar FSLIT("sh")) shape_tys
402 wilds <- mapM newDummyVar repr_tys
403 let scrut = unwrapFamInstScrut arr_tc arg_tys (Var arg)
404 scrut_ty = exprType scrut
406 body <- shapeLength shape (map Var shapes)
409 $ Case scrut (mkWildId scrut_ty) intPrimTy
410 [(DataAlt repr_dc, shapes ++ wilds, body)]
412 arg_tys = mkTyVarTys $ tyConTyVars arr_tc
413 [repr_dc] = tyConDataCons arr_tc
415 shape_tys = shapeReprTys shape
416 repr_tys = drop (length shape_tys) (dataConRepArgTys repr_dc)
418 -- data T = C0 t1 ... tm
422 -- data [:T:] = A ![:Int:] [:t1:] ... [:un:]
424 -- replicatePA :: Int# -> T -> [:T:]
426 -- = let c = case t of
432 -- C0 x1 _ ... _ -> replicatePA @t1 n# x1
438 -- Ck _ ... _ yn -> replicatePA @un n# yn
441 -- A (replicatePA @Int n# c) xs1 ... ysn
445 buildReplicatePA :: Shape -> TyCon -> TyCon -> VM CoreExpr
446 buildReplicatePA shape vect_tc arr_tc
448 len_var <- newLocalVar FSLIT("n") intPrimTy
449 val_var <- newLocalVar FSLIT("x") val_ty
451 let len = Var len_var
454 shape_reprs <- shapeReplicate shape len (ctr_num val)
455 reprs <- liftM concat $ mapM (mk_comp_arrs len val) vect_dcs
457 return . mkLams [len_var, val_var]
458 . wrapFamInstBody arr_tc arg_tys
459 $ mkConApp arr_dc (map Type arg_tys ++ shape_reprs ++ reprs)
461 arg_tys = mkTyVarTys (tyConTyVars arr_tc)
462 val_ty = mkTyConApp vect_tc arg_tys
463 wild = mkWildId val_ty
464 vect_dcs = tyConDataCons vect_tc
465 [arr_dc] = tyConDataCons arr_tc
467 ctr_num val = Case val wild intTy (zipWith ctr_num_alt vect_dcs [0..])
468 ctr_num_alt dc i = (DataAlt dc, map mkWildId (dataConRepArgTys dc),
469 mkConApp intDataCon [mkIntLitInt i])
472 mk_comp_arrs len val dc = let tys = dataConRepArgTys dc
473 wilds = map mkWildId tys
475 sequence (zipWith3 (mk_comp_arr len val dc)
476 tys (inits wilds) (tails wilds))
478 mk_comp_arr len val dc ty pre (_:post)
480 var <- newLocalVar FSLIT("x") ty
481 rep <- replicatePA len (Var var)
483 arr_ty <- mkPArrayType ty
485 return $ Case val wild arr_ty
486 [(DEFAULT, [], empty), (DataAlt dc, pre ++ (var : post), rep)]
488 -- | Split the given tycons into two sets depending on whether they have to be
489 -- converted (first list) or not (second list). The first argument contains
490 -- information about the conversion status of external tycons:
492 -- * tycons which have converted versions are mapped to True
493 -- * tycons which are not changed by vectorisation are mapped to False
494 -- * tycons which can't be converted are not elements of the map
496 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
497 classifyTyCons = classify [] []
499 classify conv keep cs [] = (conv, keep)
500 classify conv keep cs ((tcs, ds) : rs)
501 | can_convert && must_convert
502 = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
504 = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
506 = classify conv keep cs rs
508 refs = ds `delListFromUniqSet` tcs
510 can_convert = isNullUFM (refs `minusUFM` cs) && all convertable tcs
511 must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
513 convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
515 -- | Compute mutually recursive groups of tycons in topological order
517 tyConGroups :: [TyCon] -> [TyConGroup]
518 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
520 edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
521 , let ds = tyConsOfTyCon tc]
523 mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
524 mk_grp (CyclicSCC els) = (tcs, unionManyUniqSets dss)
526 (tcs, dss) = unzip els
528 tyConsOfTyCon :: TyCon -> UniqSet TyCon
530 = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
532 tyConsOfType :: Type -> UniqSet TyCon
534 | Just ty' <- coreView ty = tyConsOfType ty'
535 tyConsOfType (TyVarTy v) = emptyUniqSet
536 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
538 extend | isUnLiftedTyCon tc
539 || isTupleTyCon tc = id
541 | otherwise = (`addOneToUniqSet` tc)
543 tyConsOfType (AppTy a b) = tyConsOfType a `unionUniqSets` tyConsOfType b
544 tyConsOfType (FunTy a b) = (tyConsOfType a `unionUniqSets` tyConsOfType b)
545 `addOneToUniqSet` funTyCon
546 tyConsOfType (ForAllTy _ ty) = tyConsOfType ty
547 tyConsOfType other = pprPanic "ClosureConv.tyConsOfType" $ ppr other
549 tyConsOfTypes :: [Type] -> UniqSet TyCon
550 tyConsOfTypes = unionManyUniqSets . map tyConsOfType