Generate replicatePA
[ghc.git] / compiler / vectorise / VectType.hs
1 module VectType ( vectTyCon, vectType, vectTypeEnv )
2 where
3
4 #include "HsVersions.h"
5
6 import VectMonad
7 import VectUtils
8
9 import HscTypes ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
10 import CoreSyn
11 import DataCon
12 import TyCon
13 import Type
14 import TypeRep
15 import Coercion
16 import FamInstEnv ( FamInst, mkLocalFamInst )
17 import InstEnv ( Instance )
18 import OccName
19 import MkId
20 import BasicTypes ( StrictnessMark(..), boolToRecFlag )
21 import Id ( mkWildId )
22 import Name ( Name )
23 import NameEnv
24 import TysWiredIn ( intTy, intDataCon )
25 import TysPrim ( intPrimTy )
26
27 import Unique
28 import UniqFM
29 import UniqSet
30 import Digraph ( SCC(..), stronglyConnComp )
31
32 import Outputable
33
34 import Control.Monad ( liftM, liftM2, zipWithM, zipWithM_ )
35 import Data.List ( inits, tails )
36
37 -- ----------------------------------------------------------------------------
38 -- Types
39
40 vectTyCon :: TyCon -> VM TyCon
41 vectTyCon tc
42 | isFunTyCon tc = builtin closureTyCon
43 | isBoxedTupleTyCon tc = return tc
44 | isUnLiftedTyCon tc = return tc
45 | otherwise = do
46 r <- lookupTyCon tc
47 case r of
48 Just tc' -> return tc'
49
50 -- FIXME: just for now
51 Nothing -> pprTrace "ccTyCon:" (ppr tc) $ return tc
52
53 vectType :: Type -> VM Type
54 vectType ty | Just ty' <- coreView ty = vectType ty'
55 vectType (TyVarTy tv) = return $ TyVarTy tv
56 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
57 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
58 vectType (FunTy ty1 ty2) = liftM2 TyConApp (builtin closureTyCon)
59 (mapM vectType [ty1,ty2])
60 vectType ty@(ForAllTy _ _)
61 = do
62 mdicts <- mapM paDictArgType tyvars
63 mono_ty' <- vectType mono_ty
64 return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
65 where
66 (tyvars, mono_ty) = splitForAllTys ty
67
68 vectType ty = pprPanic "vectType:" (ppr ty)
69
70 -- ----------------------------------------------------------------------------
71 -- Type definitions
72
73 type TyConGroup = ([TyCon], UniqSet TyCon)
74
75 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [Instance])
76 vectTypeEnv env
77 = do
78 cs <- readGEnv $ mk_map . global_tycons
79 let (conv_tcs, keep_tcs) = classifyTyCons cs groups
80 keep_dcs = concatMap tyConDataCons keep_tcs
81 zipWithM_ defTyCon keep_tcs keep_tcs
82 zipWithM_ defDataCon keep_dcs keep_dcs
83 vect_tcs <- vectTyConDecls conv_tcs
84 parr_tcs1 <- zipWithM buildPArrayTyCon keep_tcs keep_tcs
85 parr_tcs2 <- zipWithM buildPArrayTyCon conv_tcs vect_tcs
86 let new_tcs = vect_tcs ++ parr_tcs1 ++ parr_tcs2
87
88 let new_env = extendTypeEnvList env
89 (map ATyCon new_tcs
90 ++ [ADataCon dc | tc <- new_tcs
91 , dc <- tyConDataCons tc])
92
93 return (new_env, map mkLocalFamInst (parr_tcs1 ++ parr_tcs2), [])
94 where
95 tycons = typeEnvTyCons env
96 groups = tyConGroups tycons
97
98 mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
99
100 keep_tc tc = let dcs = tyConDataCons tc
101 in
102 defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
103
104
105 vectTyConDecls :: [TyCon] -> VM [TyCon]
106 vectTyConDecls tcs = fixV $ \tcs' ->
107 do
108 mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
109 mapM vectTyConDecl tcs
110 where
111 lazy_zip [] _ = []
112 lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
113
114 vectTyConDecl :: TyCon -> VM TyCon
115 vectTyConDecl tc
116 = do
117 name' <- cloneName mkVectTyConOcc name
118 rhs' <- vectAlgTyConRhs (algTyConRhs tc)
119
120 return $ mkAlgTyCon name'
121 kind
122 tyvars
123 [] -- no stupid theta
124 rhs'
125 [] -- no selector ids
126 NoParentTyCon -- FIXME
127 rec_flag -- FIXME: is this ok?
128 False -- FIXME: no generics
129 False -- not GADT syntax
130 where
131 name = tyConName tc
132 kind = tyConKind tc
133 tyvars = tyConTyVars tc
134 rec_flag = boolToRecFlag (isRecursiveTyCon tc)
135
136 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
137 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
138 , is_enum = is_enum
139 })
140 = do
141 data_cons' <- mapM vectDataCon data_cons
142 zipWithM_ defDataCon data_cons data_cons'
143 return $ DataTyCon { data_cons = data_cons'
144 , is_enum = is_enum
145 }
146
147 vectDataCon :: DataCon -> VM DataCon
148 vectDataCon dc
149 | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
150 | not . null $ dataConEqSpec dc = pprPanic "vectDataCon: eq spec" (ppr dc)
151 | otherwise
152 = do
153 name' <- cloneName mkVectDataConOcc name
154 tycon' <- vectTyCon tycon
155 arg_tys <- mapM vectType rep_arg_tys
156 wrk_name <- cloneName mkDataConWorkerOcc name'
157
158 let ids = mkDataConIds (panic "vectDataCon: wrapper id")
159 wrk_name
160 data_con
161 data_con = mkDataCon name'
162 False -- not infix
163 (map (const NotMarkedStrict) arg_tys)
164 [] -- no labelled fields
165 univ_tvs
166 [] -- no existential tvs for now
167 [] -- no eq spec for now
168 [] -- no theta
169 arg_tys
170 tycon'
171 [] -- no stupid theta
172 ids
173 return data_con
174 where
175 name = dataConName dc
176 univ_tvs = dataConUnivTyVars dc
177 rep_arg_tys = dataConRepArgTys dc
178 tycon = dataConTyCon dc
179
180 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
181 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
182 do
183 name' <- cloneName mkPArrayTyConOcc orig_name
184 parent <- buildPArrayParentInfo orig_name vect_tc repr_tc
185 rhs <- buildPArrayTyConRhs orig_name vect_tc repr_tc
186
187 return $ mkAlgTyCon name'
188 kind
189 tyvars
190 [] -- no stupid theta
191 rhs
192 [] -- no selector ids
193 parent
194 rec_flag -- FIXME: is this ok?
195 False -- FIXME: no generics
196 False -- not GADT syntax
197 where
198 orig_name = tyConName orig_tc
199 name = tyConName vect_tc
200 kind = tyConKind vect_tc
201 tyvars = tyConTyVars vect_tc
202 rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
203
204
205 buildPArrayParentInfo :: Name -> TyCon -> TyCon -> VM TyConParent
206 buildPArrayParentInfo orig_name vect_tc repr_tc
207 = do
208 parray_tc <- builtin parrayTyCon
209 co_name <- cloneName mkInstTyCoOcc (tyConName repr_tc)
210
211 let inst_tys = [mkTyConApp vect_tc (map mkTyVarTy tyvars)]
212
213 return . FamilyTyCon parray_tc inst_tys
214 $ mkFamInstCoercion co_name
215 tyvars
216 parray_tc
217 inst_tys
218 repr_tc
219 where
220 tyvars = tyConTyVars vect_tc
221
222 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
223 buildPArrayTyConRhs orig_name vect_tc repr_tc
224 = do
225 data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
226 return $ DataTyCon { data_cons = [data_con], is_enum = False }
227
228 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
229 buildPArrayDataCon orig_name vect_tc repr_tc
230 = do
231 dc_name <- cloneName mkPArrayDataConOcc orig_name
232 shape_ty <- mkPArrayType intTy -- FIXME: we want to unbox this!
233 repr_tys <- mapM mkPArrayType types
234 wrk_name <- cloneName mkDataConWorkerOcc dc_name
235 wrp_name <- cloneName mkDataConWrapperOcc dc_name
236
237 let ids = mkDataConIds wrp_name wrk_name data_con
238 data_con = mkDataCon dc_name
239 False
240 (MarkedStrict : map (const NotMarkedStrict) repr_tys)
241 []
242 (tyConTyVars vect_tc)
243 []
244 []
245 []
246 (shape_ty : repr_tys)
247 repr_tc
248 []
249 ids
250
251 return data_con
252 where
253 types = [ty | dc <- tyConDataCons vect_tc
254 , ty <- dataConRepArgTys dc]
255
256 buildLengthPA :: TyCon -> VM CoreExpr
257 buildLengthPA repr_tc
258 = do
259 arg <- newLocalVar FSLIT("xs") arg_ty
260 shape <- newLocalVar FSLIT("sel") shape_ty
261 body <- lengthPA (Var shape)
262 return . Lam arg
263 $ Case (Var arg) (mkWildId arg_ty) intPrimTy
264 [(DataAlt repr_dc, shape : map mkWildId repr_tys, body)]
265 where
266 arg_ty = mkTyConApp repr_tc . mkTyVarTys $ tyConTyVars repr_tc
267 [repr_dc] = tyConDataCons repr_tc
268 shape_ty : repr_tys = dataConRepArgTys repr_dc
269
270
271 -- data T = C0 t1 ... tm
272 -- ...
273 -- Ck u1 ... un
274 --
275 -- data [:T:] = A ![:Int:] [:t1:] ... [:un:]
276 --
277 -- replicatePA :: Int# -> T -> [:T:]
278 -- replicatePA n# t
279 -- = let c = case t of
280 -- C0 _ ... _ -> 0
281 -- ...
282 -- Ck _ ... _ -> k
283 --
284 -- xs1 = case t of
285 -- C0 x1 _ ... _ -> replicatePA @t1 n# x1
286 -- _ -> emptyPA @t1
287 --
288 -- ...
289 --
290 -- ysn = case t of
291 -- Ck _ ... _ yn -> replicatePA @un n# yn
292 -- _ -> emptyPA @un
293 -- in
294 -- A (replicatePA @Int n# c) xs1 ... ysn
295 --
296 --
297
298 buildReplicatePA :: TyCon -> TyCon -> VM CoreExpr
299 buildReplicatePA vect_tc arr_tc
300 = do
301 len_var <- newLocalVar FSLIT("n") intPrimTy
302 val_var <- newLocalVar FSLIT("x") val_ty
303
304 let len = Var len_var
305 val = Var val_var
306
307 shape <- replicatePA len (ctr_num val)
308 reprs <- liftM concat $ mapM (mk_comp_arrs len val) vect_dcs
309
310 return . mkLams [len_var, val_var]
311 $ mkConApp arr_dc (map (Type . TyVarTy) (tyConTyVars arr_tc) ++ (shape : reprs))
312 where
313 val_ty = mkTyConApp vect_tc . mkTyVarTys $ tyConTyVars arr_tc
314 wild = mkWildId val_ty
315 vect_dcs = tyConDataCons vect_tc
316 [arr_dc] = tyConDataCons arr_tc
317
318 ctr_num val = Case val wild intTy (zipWith ctr_num_alt vect_dcs [0..])
319 ctr_num_alt dc i = (DataAlt dc, map mkWildId (dataConRepArgTys dc),
320 mkConApp intDataCon [mkIntLitInt i])
321
322
323 mk_comp_arrs len val dc = let tys = dataConRepArgTys dc
324 wilds = map mkWildId tys
325 in
326 sequence (zipWith3 (mk_comp_arr len val dc)
327 tys (inits wilds) (tails wilds))
328
329 mk_comp_arr len val dc ty pre (_:post)
330 = do
331 var <- newLocalVar FSLIT("x") ty
332 rep <- replicatePA len (Var var)
333 empty <- emptyPA ty
334 arr_ty <- mkPArrayType ty
335
336 return $ Case val wild arr_ty
337 [(DataAlt dc, pre ++ (var : post), rep), (DEFAULT, [], empty)]
338
339 -- | Split the given tycons into two sets depending on whether they have to be
340 -- converted (first list) or not (second list). The first argument contains
341 -- information about the conversion status of external tycons:
342 --
343 -- * tycons which have converted versions are mapped to True
344 -- * tycons which are not changed by vectorisation are mapped to False
345 -- * tycons which can't be converted are not elements of the map
346 --
347 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
348 classifyTyCons = classify [] []
349 where
350 classify conv keep cs [] = (conv, keep)
351 classify conv keep cs ((tcs, ds) : rs)
352 | can_convert && must_convert
353 = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
354 | can_convert
355 = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
356 | otherwise
357 = classify conv keep cs rs
358 where
359 refs = ds `delListFromUniqSet` tcs
360
361 can_convert = isNullUFM (refs `minusUFM` cs) && all convertable tcs
362 must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
363
364 convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
365
366 -- | Compute mutually recursive groups of tycons in topological order
367 --
368 tyConGroups :: [TyCon] -> [TyConGroup]
369 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
370 where
371 edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
372 , let ds = tyConsOfTyCon tc]
373
374 mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
375 mk_grp (CyclicSCC els) = (tcs, unionManyUniqSets dss)
376 where
377 (tcs, dss) = unzip els
378
379 tyConsOfTyCon :: TyCon -> UniqSet TyCon
380 tyConsOfTyCon
381 = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
382
383 tyConsOfType :: Type -> UniqSet TyCon
384 tyConsOfType ty
385 | Just ty' <- coreView ty = tyConsOfType ty'
386 tyConsOfType (TyVarTy v) = emptyUniqSet
387 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
388 where
389 extend | isUnLiftedTyCon tc
390 || isTupleTyCon tc = id
391
392 | otherwise = (`addOneToUniqSet` tc)
393
394 tyConsOfType (AppTy a b) = tyConsOfType a `unionUniqSets` tyConsOfType b
395 tyConsOfType (FunTy a b) = (tyConsOfType a `unionUniqSets` tyConsOfType b)
396 `addOneToUniqSet` funTyCon
397 tyConsOfType (ForAllTy _ ty) = tyConsOfType ty
398 tyConsOfType other = pprPanic "ClosureConv.tyConsOfType" $ ppr other
399
400 tyConsOfTypes :: [Type] -> UniqSet TyCon
401 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
402