1 module VectType ( vectTyCon, vectType, vectTypeEnv,
2 PAInstance, painstInstance, buildPADict )
5 #include "HsVersions.h"
10 import HscTypes ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
18 import FamInstEnv ( FamInst, mkLocalFamInst )
19 import InstEnv ( Instance, mkLocalInstance, instanceDFunId )
22 import BasicTypes ( StrictnessMark(..), OverlapFlag(..), boolToRecFlag )
24 import Id ( mkWildId )
25 import Name ( Name, getOccName )
27 import TysWiredIn ( intTy, intDataCon )
28 import TysPrim ( intPrimTy )
33 import Digraph ( SCC(..), stronglyConnComp )
37 import Control.Monad ( liftM, liftM2, zipWithM, zipWithM_ )
38 import Data.List ( inits, tails )
40 -- ----------------------------------------------------------------------------
43 vectTyCon :: TyCon -> VM TyCon
45 | isFunTyCon tc = builtin closureTyCon
46 | isBoxedTupleTyCon tc = return tc
47 | isUnLiftedTyCon tc = return tc
51 Just tc' -> return tc'
53 -- FIXME: just for now
54 Nothing -> pprTrace "ccTyCon:" (ppr tc) $ return tc
56 vectType :: Type -> VM Type
57 vectType ty | Just ty' <- coreView ty = vectType ty'
58 vectType (TyVarTy tv) = return $ TyVarTy tv
59 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
60 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
61 vectType (FunTy ty1 ty2) = liftM2 TyConApp (builtin closureTyCon)
62 (mapM vectType [ty1,ty2])
63 vectType ty@(ForAllTy _ _)
65 mdicts <- mapM paDictArgType tyvars
66 mono_ty' <- vectType mono_ty
67 return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
69 (tyvars, mono_ty) = splitForAllTys ty
71 vectType ty = pprPanic "vectType:" (ppr ty)
73 -- ----------------------------------------------------------------------------
76 type TyConGroup = ([TyCon], UniqSet TyCon)
78 data PAInstance = PAInstance {
79 painstInstance :: Instance
80 , painstVectTyCon :: TyCon
81 , painstArrTyCon :: TyCon
84 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [PAInstance])
87 cs <- readGEnv $ mk_map . global_tycons
88 let (conv_tcs, keep_tcs) = classifyTyCons cs groups
89 keep_dcs = concatMap tyConDataCons keep_tcs
90 zipWithM_ defTyCon keep_tcs keep_tcs
91 zipWithM_ defDataCon keep_dcs keep_dcs
92 new_tcs <- vectTyConDecls conv_tcs
94 let orig_tcs = keep_tcs ++ conv_tcs
95 vect_tcs = keep_tcs ++ new_tcs
97 parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
98 pa_insts <- zipWithM buildPAInstance vect_tcs parr_tcs
100 let all_new_tcs = new_tcs ++ parr_tcs
102 let new_env = extendTypeEnvList env
103 (map ATyCon all_new_tcs
104 ++ [ADataCon dc | tc <- all_new_tcs
105 , dc <- tyConDataCons tc])
107 return (new_env, map mkLocalFamInst parr_tcs, pa_insts)
109 tycons = typeEnvTyCons env
110 groups = tyConGroups tycons
112 mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
114 keep_tc tc = let dcs = tyConDataCons tc
116 defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
119 vectTyConDecls :: [TyCon] -> VM [TyCon]
120 vectTyConDecls tcs = fixV $ \tcs' ->
122 mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
123 mapM vectTyConDecl tcs
126 lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
128 vectTyConDecl :: TyCon -> VM TyCon
131 name' <- cloneName mkVectTyConOcc name
132 rhs' <- vectAlgTyConRhs (algTyConRhs tc)
134 return $ mkAlgTyCon name'
137 [] -- no stupid theta
139 [] -- no selector ids
140 NoParentTyCon -- FIXME
141 rec_flag -- FIXME: is this ok?
142 False -- FIXME: no generics
143 False -- not GADT syntax
147 tyvars = tyConTyVars tc
148 rec_flag = boolToRecFlag (isRecursiveTyCon tc)
150 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
151 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
155 data_cons' <- mapM vectDataCon data_cons
156 zipWithM_ defDataCon data_cons data_cons'
157 return $ DataTyCon { data_cons = data_cons'
161 vectDataCon :: DataCon -> VM DataCon
163 | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
164 | not . null $ dataConEqSpec dc = pprPanic "vectDataCon: eq spec" (ppr dc)
167 name' <- cloneName mkVectDataConOcc name
168 tycon' <- vectTyCon tycon
169 arg_tys <- mapM vectType rep_arg_tys
170 wrk_name <- cloneName mkDataConWorkerOcc name'
172 let ids = mkDataConIds (panic "vectDataCon: wrapper id")
175 data_con = mkDataCon name'
177 (map (const NotMarkedStrict) arg_tys)
178 [] -- no labelled fields
180 [] -- no existential tvs for now
181 [] -- no eq spec for now
185 [] -- no stupid theta
189 name = dataConName dc
190 univ_tvs = dataConUnivTyVars dc
191 rep_arg_tys = dataConRepArgTys dc
192 tycon = dataConTyCon dc
194 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
195 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
197 name' <- cloneName mkPArrayTyConOcc orig_name
198 parent <- buildPArrayParentInfo orig_name vect_tc repr_tc
199 rhs <- buildPArrayTyConRhs orig_name vect_tc repr_tc
201 return $ mkAlgTyCon name'
204 [] -- no stupid theta
206 [] -- no selector ids
208 rec_flag -- FIXME: is this ok?
209 False -- FIXME: no generics
210 False -- not GADT syntax
212 orig_name = tyConName orig_tc
213 name = tyConName vect_tc
214 kind = tyConKind vect_tc
215 tyvars = tyConTyVars vect_tc
216 rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
219 buildPArrayParentInfo :: Name -> TyCon -> TyCon -> VM TyConParent
220 buildPArrayParentInfo orig_name vect_tc repr_tc
222 parray_tc <- builtin parrayTyCon
223 co_name <- cloneName mkInstTyCoOcc (tyConName repr_tc)
225 let inst_tys = [mkTyConApp vect_tc (map mkTyVarTy tyvars)]
227 return . FamilyTyCon parray_tc inst_tys
228 $ mkFamInstCoercion co_name
234 tyvars = tyConTyVars vect_tc
236 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
237 buildPArrayTyConRhs orig_name vect_tc repr_tc
239 data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
240 return $ DataTyCon { data_cons = [data_con], is_enum = False }
242 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
243 buildPArrayDataCon orig_name vect_tc repr_tc
245 dc_name <- cloneName mkPArrayDataConOcc orig_name
246 shape_ty <- mkPArrayType intTy -- FIXME: we want to unbox this!
247 repr_tys <- mapM mkPArrayType types
248 wrk_name <- cloneName mkDataConWorkerOcc dc_name
249 wrp_name <- cloneName mkDataConWrapperOcc dc_name
251 let ids = mkDataConIds wrp_name wrk_name data_con
252 data_con = mkDataCon dc_name
254 (MarkedStrict : map (const NotMarkedStrict) repr_tys)
256 (tyConTyVars vect_tc)
260 (shape_ty : repr_tys)
267 types = [ty | dc <- tyConDataCons vect_tc
268 , ty <- dataConRepArgTys dc]
270 buildPAInstance :: TyCon -> TyCon -> VM PAInstance
271 buildPAInstance vect_tc arr_tc
273 pa <- builtin paClass
274 let inst_ty = mkForAllTys tvs
275 . (mkFunTys $ mkPredTys [ClassP pa [ty] | ty <- arg_tys])
276 $ mkPredTy (ClassP pa [mkTyConApp vect_tc arg_tys])
278 dfun <- newExportedVar (mkPADFunOcc $ getOccName vect_tc) inst_ty
280 return $ PAInstance {
281 painstInstance = mkLocalInstance dfun NoOverlap
282 , painstVectTyCon = vect_tc
283 , painstArrTyCon = arr_tc
286 tvs = tyConTyVars arr_tc
287 arg_tys = mkTyVarTys tvs
289 buildPADict :: PAInstance -> VM [(Var, CoreExpr)]
290 buildPADict (PAInstance {
291 painstInstance = inst
292 , painstVectTyCon = vect_tc
293 , painstArrTyCon = arr_tc })
294 = localV . abstractOverTyVars (tyConTyVars arr_tc) $ \abstract ->
296 meth_binds <- mapM mk_method paMethods
297 let meth_exprs = map (Var . fst) meth_binds
299 pa_dc <- builtin paDictDataCon
300 let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
301 body = Let (Rec meth_binds) dict
302 return [(instanceDFunId inst, mkInlineMe $ abstract body)]
304 tvs = tyConTyVars arr_tc
305 arg_tys = mkTyVarTys tvs
307 mk_method (name, build)
310 body <- build vect_tc arr_tc
311 var <- newLocalVar name (exprType body)
312 return (var, mkInlineMe body)
314 paMethods = [(FSLIT("lengthPA"), buildLengthPA),
315 (FSLIT("replicatePA"), buildReplicatePA)]
317 buildLengthPA :: TyCon -> TyCon -> VM CoreExpr
318 buildLengthPA vect_tc arr_tc
320 parr_ty <- mkPArrayType (mkTyConApp vect_tc arg_tys)
321 arg <- newLocalVar FSLIT("xs") parr_ty
322 let scrut = unwrapFamInstScrut arr_tc arg_tys (Var arg)
323 scrut_ty = exprType scrut
324 shape <- newLocalVar FSLIT("sel") shape_ty
325 body <- lengthPA (Var shape)
326 wilds <- mapM newDummyVar repr_tys
328 $ Case scrut (mkWildId scrut_ty) intPrimTy
329 [(DataAlt repr_dc, shape : wilds, body)]
331 arg_tys = mkTyVarTys $ tyConTyVars arr_tc
332 [repr_dc] = tyConDataCons arr_tc
333 shape_ty : repr_tys = dataConRepArgTys repr_dc
335 -- data T = C0 t1 ... tm
339 -- data [:T:] = A ![:Int:] [:t1:] ... [:un:]
341 -- replicatePA :: Int# -> T -> [:T:]
343 -- = let c = case t of
349 -- C0 x1 _ ... _ -> replicatePA @t1 n# x1
355 -- Ck _ ... _ yn -> replicatePA @un n# yn
358 -- A (replicatePA @Int n# c) xs1 ... ysn
362 buildReplicatePA :: TyCon -> TyCon -> VM CoreExpr
363 buildReplicatePA vect_tc arr_tc
365 len_var <- newLocalVar FSLIT("n") intPrimTy
366 val_var <- newLocalVar FSLIT("x") val_ty
368 let len = Var len_var
371 shape <- replicatePA len (ctr_num val)
372 reprs <- liftM concat $ mapM (mk_comp_arrs len val) vect_dcs
374 return . mkLams [len_var, val_var]
375 . wrapFamInstBody arr_tc arg_tys
376 $ mkConApp arr_dc (map Type arg_tys ++ (shape : reprs))
378 arg_tys = mkTyVarTys (tyConTyVars arr_tc)
379 val_ty = mkTyConApp vect_tc arg_tys
380 wild = mkWildId val_ty
381 vect_dcs = tyConDataCons vect_tc
382 [arr_dc] = tyConDataCons arr_tc
384 ctr_num val = Case val wild intTy (zipWith ctr_num_alt vect_dcs [0..])
385 ctr_num_alt dc i = (DataAlt dc, map mkWildId (dataConRepArgTys dc),
386 mkConApp intDataCon [mkIntLitInt i])
389 mk_comp_arrs len val dc = let tys = dataConRepArgTys dc
390 wilds = map mkWildId tys
392 sequence (zipWith3 (mk_comp_arr len val dc)
393 tys (inits wilds) (tails wilds))
395 mk_comp_arr len val dc ty pre (_:post)
397 var <- newLocalVar FSLIT("x") ty
398 rep <- replicatePA len (Var var)
400 arr_ty <- mkPArrayType ty
402 return $ Case val wild arr_ty
403 [(DEFAULT, [], empty), (DataAlt dc, pre ++ (var : post), rep)]
405 -- | Split the given tycons into two sets depending on whether they have to be
406 -- converted (first list) or not (second list). The first argument contains
407 -- information about the conversion status of external tycons:
409 -- * tycons which have converted versions are mapped to True
410 -- * tycons which are not changed by vectorisation are mapped to False
411 -- * tycons which can't be converted are not elements of the map
413 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
414 classifyTyCons = classify [] []
416 classify conv keep cs [] = (conv, keep)
417 classify conv keep cs ((tcs, ds) : rs)
418 | can_convert && must_convert
419 = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
421 = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
423 = classify conv keep cs rs
425 refs = ds `delListFromUniqSet` tcs
427 can_convert = isNullUFM (refs `minusUFM` cs) && all convertable tcs
428 must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
430 convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
432 -- | Compute mutually recursive groups of tycons in topological order
434 tyConGroups :: [TyCon] -> [TyConGroup]
435 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
437 edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
438 , let ds = tyConsOfTyCon tc]
440 mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
441 mk_grp (CyclicSCC els) = (tcs, unionManyUniqSets dss)
443 (tcs, dss) = unzip els
445 tyConsOfTyCon :: TyCon -> UniqSet TyCon
447 = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
449 tyConsOfType :: Type -> UniqSet TyCon
451 | Just ty' <- coreView ty = tyConsOfType ty'
452 tyConsOfType (TyVarTy v) = emptyUniqSet
453 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
455 extend | isUnLiftedTyCon tc
456 || isTupleTyCon tc = id
458 | otherwise = (`addOneToUniqSet` tc)
460 tyConsOfType (AppTy a b) = tyConsOfType a `unionUniqSets` tyConsOfType b
461 tyConsOfType (FunTy a b) = (tyConsOfType a `unionUniqSets` tyConsOfType b)
462 `addOneToUniqSet` funTyCon
463 tyConsOfType (ForAllTy _ ty) = tyConsOfType ty
464 tyConsOfType other = pprPanic "ClosureConv.tyConsOfType" $ ppr other
466 tyConsOfTypes :: [Type] -> UniqSet TyCon
467 tyConsOfTypes = unionManyUniqSets . map tyConsOfType