1 module VectType ( vectTyCon, vectType, vectTypeEnv,
2 PAInstance, buildPADict,
6 #include "HsVersions.h"
12 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 ( 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 )
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])
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 parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
101 dfuns <- mapM mkPADFun vect_tcs
102 defTyConPAs (zip vect_tcs dfuns)
103 -- pa_insts <- sequence $ zipWith3 buildPAInstance orig_tcs vect_tcs parr_tcs
105 let all_new_tcs = new_tcs ++ parr_tcs
107 let new_env = extendTypeEnvList env
108 (map ATyCon all_new_tcs
109 ++ [ADataCon dc | tc <- all_new_tcs
110 , dc <- tyConDataCons tc])
112 return (new_env, map mkLocalFamInst parr_tcs)
114 tycons = typeEnvTyCons env
115 groups = tyConGroups tycons
117 mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
119 keep_tc tc = let dcs = tyConDataCons tc
121 defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
124 vectTyConDecls :: [TyCon] -> VM [TyCon]
125 vectTyConDecls tcs = fixV $ \tcs' ->
127 mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
128 mapM vectTyConDecl tcs
131 lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
133 vectTyConDecl :: TyCon -> VM TyCon
136 name' <- cloneName mkVectTyConOcc name
137 rhs' <- vectAlgTyConRhs (algTyConRhs tc)
139 return $ mkAlgTyCon name'
142 [] -- no stupid theta
144 [] -- no selector ids
145 NoParentTyCon -- FIXME
146 rec_flag -- FIXME: is this ok?
147 False -- FIXME: no generics
148 False -- not GADT syntax
152 tyvars = tyConTyVars tc
153 rec_flag = boolToRecFlag (isRecursiveTyCon tc)
155 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
156 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
160 data_cons' <- mapM vectDataCon data_cons
161 zipWithM_ defDataCon data_cons data_cons'
162 return $ DataTyCon { data_cons = data_cons'
166 vectDataCon :: DataCon -> VM DataCon
168 | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
169 | not . null $ dataConEqSpec dc = pprPanic "vectDataCon: eq spec" (ppr dc)
172 name' <- cloneName mkVectDataConOcc name
173 tycon' <- vectTyCon tycon
174 arg_tys <- mapM vectType rep_arg_tys
175 wrk_name <- cloneName mkDataConWorkerOcc name'
177 let ids = mkDataConIds (panic "vectDataCon: wrapper id")
180 data_con = mkDataCon name'
182 (map (const NotMarkedStrict) arg_tys)
183 [] -- no labelled fields
185 [] -- no existential tvs for now
186 [] -- no eq spec for now
190 [] -- no stupid theta
194 name = dataConName dc
195 univ_tvs = dataConUnivTyVars dc
196 rep_arg_tys = dataConRepArgTys dc
197 tycon = dataConTyCon dc
199 vectDataConWorkers :: PAInstance -> VM [(Var, CoreExpr)]
200 vectDataConWorkers (PAInstance { painstOrigTyCon = orig_tc
201 , painstVectTyCon = vect_tc
202 , painstArrTyCon = arr_tc
205 shape <- tyConShape vect_tc
206 sequence_ (zipWith3 (vectDataConWorker shape vect_tc arr_tc arr_dc)
212 orig_dcs = tyConDataCons orig_tc
213 vect_dcs = tyConDataCons vect_tc
214 [arr_dc] = tyConDataCons arr_tc
216 num_dcs = zip3 orig_dcs vect_dcs [0..]
217 repr_tys = map dataConRepArgTys vect_dcs
219 vectDataConWorker :: Shape -> TyCon -> TyCon -> DataCon
220 -> (DataCon, DataCon, Int) -> [[Type]] -> [[Type]]
222 vectDataConWorker shape vect_tc arr_tc arr_dc (orig_dc, vect_dc, dc_num) pre (dc_tys : post)
226 . polyAbstract tvs $ \abstract ->
227 liftM (abstract . vectorised)
228 $ buildClosures tvs [] dc_tys res_ty (liftM2 (,) mk_vect mk_lift)
230 worker <- cloneId mkVectOcc orig_worker (exprType clo)
231 hoistBinding worker clo
232 defGlobalVar orig_worker worker
235 tvs = tyConTyVars vect_tc
236 arg_tys = mkTyVarTys tvs
237 res_ty = mkTyConApp vect_tc arg_tys
239 orig_worker = dataConWorkId orig_dc
241 mk_vect = return . mkConApp vect_dc $ map Type arg_tys
243 len <- newLocalVar FSLIT("n") intPrimTy
244 arr_tys <- mapM mkPArrayType dc_tys
245 args <- mapM (newLocalVar FSLIT("xs")) arr_tys
246 shapes <- shapeReplicate shape (Var len) (mkIntLitInt dc_num)
248 empty_pre <- mapM emptyPA (concat pre)
249 empty_post <- mapM emptyPA (concat post)
251 return . mkLams (len : args)
252 . wrapFamInstBody arr_tc arg_tys
254 $ map Type arg_tys ++ shapes
260 shapeReprTys :: [Type]
261 , shapeStrictness :: [StrictnessMark]
262 , shapeLength :: [CoreExpr] -> VM CoreExpr
263 , shapeReplicate :: CoreExpr -> CoreExpr -> VM [CoreExpr]
266 tyConShape :: TyCon -> VM Shape
268 | isProductTyCon vect_tc
270 shapeReprTys = [intPrimTy]
271 , shapeStrictness = [NotMarkedStrict]
272 , shapeLength = \[len] -> return len
273 , shapeReplicate = \len _ -> return [len]
278 repr_ty <- mkPArrayType intTy -- FIXME: we want to unbox this
280 shapeReprTys = [repr_ty]
281 , shapeStrictness = [MarkedStrict]
282 , shapeLength = \[sel] -> lengthPA sel
283 , shapeReplicate = \len n -> do
284 e <- replicatePA len n
288 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
289 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
291 name' <- cloneName mkPArrayTyConOcc orig_name
292 parent <- buildPArrayParentInfo orig_name vect_tc repr_tc
293 rhs <- buildPArrayTyConRhs orig_name vect_tc repr_tc
295 return $ mkAlgTyCon name'
298 [] -- no stupid theta
300 [] -- no selector ids
302 rec_flag -- FIXME: is this ok?
303 False -- FIXME: no generics
304 False -- not GADT syntax
306 orig_name = tyConName orig_tc
307 name = tyConName vect_tc
308 kind = tyConKind vect_tc
309 tyvars = tyConTyVars vect_tc
310 rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
313 buildPArrayParentInfo :: Name -> TyCon -> TyCon -> VM TyConParent
314 buildPArrayParentInfo orig_name vect_tc repr_tc
316 parray_tc <- builtin parrayTyCon
317 co_name <- cloneName mkInstTyCoOcc (tyConName repr_tc)
319 let inst_tys = [mkTyConApp vect_tc (map mkTyVarTy tyvars)]
321 return . FamilyTyCon parray_tc inst_tys
322 $ mkFamInstCoercion co_name
328 tyvars = tyConTyVars vect_tc
330 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
331 buildPArrayTyConRhs orig_name vect_tc repr_tc
333 data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
334 return $ DataTyCon { data_cons = [data_con], is_enum = False }
336 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
337 buildPArrayDataCon orig_name vect_tc repr_tc
339 dc_name <- cloneName mkPArrayDataConOcc orig_name
340 shape <- tyConShape vect_tc
341 repr_tys <- mapM mkPArrayType types
342 wrk_name <- cloneName mkDataConWorkerOcc dc_name
343 wrp_name <- cloneName mkDataConWrapperOcc dc_name
345 let ids = mkDataConIds wrp_name wrk_name data_con
346 data_con = mkDataCon dc_name
348 (shapeStrictness shape ++ map (const NotMarkedStrict) repr_tys)
350 (tyConTyVars vect_tc)
354 (shapeReprTys shape ++ repr_tys)
361 types = [ty | dc <- tyConDataCons vect_tc
362 , ty <- dataConRepArgTys dc]
364 mkPADFun :: TyCon -> VM Var
366 = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
368 buildPAInstance :: TyCon -> TyCon -> TyCon -> VM PAInstance
369 buildPAInstance orig_tc vect_tc arr_tc
371 dfun_ty <- paDFunType vect_tc
372 dfun <- newExportedVar (mkPADFunOcc $ getOccName vect_tc) dfun_ty
374 return $ PAInstance {
376 , painstOrigTyCon = orig_tc
377 , painstVectTyCon = vect_tc
378 , painstArrTyCon = arr_tc
381 buildPADict :: PAInstance -> VM [(Var, CoreExpr)]
382 buildPADict (PAInstance {
384 , painstVectTyCon = vect_tc
385 , painstArrTyCon = arr_tc })
386 = polyAbstract (tyConTyVars arr_tc) $ \abstract ->
388 shape <- tyConShape vect_tc
389 meth_binds <- mapM (mk_method shape) paMethods
390 let meth_exprs = map (Var . fst) meth_binds
392 pa_dc <- builtin paDataCon
393 let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
394 body = Let (Rec meth_binds) dict
395 return [(dfun, mkInlineMe $ abstract body)]
397 tvs = tyConTyVars arr_tc
398 arg_tys = mkTyVarTys tvs
400 mk_method shape (name, build)
403 body <- build shape vect_tc arr_tc
404 var <- newLocalVar name (exprType body)
405 return (var, mkInlineMe body)
407 paMethods = [(FSLIT("lengthPA"), buildLengthPA),
408 (FSLIT("replicatePA"), buildReplicatePA)]
410 buildLengthPA :: Shape -> TyCon -> TyCon -> VM CoreExpr
411 buildLengthPA shape vect_tc arr_tc
413 parr_ty <- mkPArrayType (mkTyConApp vect_tc arg_tys)
414 arg <- newLocalVar FSLIT("xs") parr_ty
415 shapes <- mapM (newLocalVar FSLIT("sh")) shape_tys
416 wilds <- mapM newDummyVar repr_tys
417 let scrut = unwrapFamInstScrut arr_tc arg_tys (Var arg)
418 scrut_ty = exprType scrut
420 body <- shapeLength shape (map Var shapes)
423 $ Case scrut (mkWildId scrut_ty) intPrimTy
424 [(DataAlt repr_dc, shapes ++ wilds, body)]
426 arg_tys = mkTyVarTys $ tyConTyVars arr_tc
427 [repr_dc] = tyConDataCons arr_tc
429 shape_tys = shapeReprTys shape
430 repr_tys = drop (length shape_tys) (dataConRepArgTys repr_dc)
432 -- data T = C0 t1 ... tm
436 -- data [:T:] = A ![:Int:] [:t1:] ... [:un:]
438 -- replicatePA :: Int# -> T -> [:T:]
440 -- = let c = case t of
446 -- C0 x1 _ ... _ -> replicatePA @t1 n# x1
452 -- Ck _ ... _ yn -> replicatePA @un n# yn
455 -- A (replicatePA @Int n# c) xs1 ... ysn
459 buildReplicatePA :: Shape -> TyCon -> TyCon -> VM CoreExpr
460 buildReplicatePA shape vect_tc arr_tc
462 len_var <- newLocalVar FSLIT("n") intPrimTy
463 val_var <- newLocalVar FSLIT("x") val_ty
465 let len = Var len_var
468 shape_reprs <- shapeReplicate shape len (ctr_num val)
469 reprs <- liftM concat $ mapM (mk_comp_arrs len val) vect_dcs
471 return . mkLams [len_var, val_var]
472 . wrapFamInstBody arr_tc arg_tys
473 $ mkConApp arr_dc (map Type arg_tys ++ shape_reprs ++ reprs)
475 arg_tys = mkTyVarTys (tyConTyVars arr_tc)
476 val_ty = mkTyConApp vect_tc arg_tys
477 wild = mkWildId val_ty
478 vect_dcs = tyConDataCons vect_tc
479 [arr_dc] = tyConDataCons arr_tc
481 ctr_num val = Case val wild intTy (zipWith ctr_num_alt vect_dcs [0..])
482 ctr_num_alt dc i = (DataAlt dc, map mkWildId (dataConRepArgTys dc),
483 mkConApp intDataCon [mkIntLitInt i])
486 mk_comp_arrs len val dc = let tys = dataConRepArgTys dc
487 wilds = map mkWildId tys
489 sequence (zipWith3 (mk_comp_arr len val dc)
490 tys (inits wilds) (tails wilds))
492 mk_comp_arr len val dc ty pre (_:post)
494 var <- newLocalVar FSLIT("x") ty
495 rep <- replicatePA len (Var var)
497 arr_ty <- mkPArrayType ty
499 return $ Case val wild arr_ty
500 [(DEFAULT, [], empty), (DataAlt dc, pre ++ (var : post), rep)]
502 -- | Split the given tycons into two sets depending on whether they have to be
503 -- converted (first list) or not (second list). The first argument contains
504 -- information about the conversion status of external tycons:
506 -- * tycons which have converted versions are mapped to True
507 -- * tycons which are not changed by vectorisation are mapped to False
508 -- * tycons which can't be converted are not elements of the map
510 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
511 classifyTyCons = classify [] []
513 classify conv keep cs [] = (conv, keep)
514 classify conv keep cs ((tcs, ds) : rs)
515 | can_convert && must_convert
516 = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
518 = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
520 = classify conv keep cs rs
522 refs = ds `delListFromUniqSet` tcs
524 can_convert = isNullUFM (refs `minusUFM` cs) && all convertable tcs
525 must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
527 convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
529 -- | Compute mutually recursive groups of tycons in topological order
531 tyConGroups :: [TyCon] -> [TyConGroup]
532 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
534 edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
535 , let ds = tyConsOfTyCon tc]
537 mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
538 mk_grp (CyclicSCC els) = (tcs, unionManyUniqSets dss)
540 (tcs, dss) = unzip els
542 tyConsOfTyCon :: TyCon -> UniqSet TyCon
544 = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
546 tyConsOfType :: Type -> UniqSet TyCon
548 | Just ty' <- coreView ty = tyConsOfType ty'
549 tyConsOfType (TyVarTy v) = emptyUniqSet
550 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
552 extend | isUnLiftedTyCon tc
553 || isTupleTyCon tc = id
555 | otherwise = (`addOneToUniqSet` tc)
557 tyConsOfType (AppTy a b) = tyConsOfType a `unionUniqSets` tyConsOfType b
558 tyConsOfType (FunTy a b) = (tyConsOfType a `unionUniqSets` tyConsOfType b)
559 `addOneToUniqSet` funTyCon
560 tyConsOfType (ForAllTy _ ty) = tyConsOfType ty
561 tyConsOfType other = pprPanic "ClosureConv.tyConsOfType" $ ppr other
563 tyConsOfTypes :: [Type] -> UniqSet TyCon
564 tyConsOfTypes = unionManyUniqSets . map tyConsOfType