Refactoring
[ghc-hetmet.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 DataCon
11 import TyCon
12 import Type
13 import TypeRep
14 import Coercion
15 import FamInstEnv        ( FamInst, mkLocalFamInst )
16 import InstEnv           ( Instance )
17 import OccName
18 import MkId
19 import BasicTypes        ( StrictnessMark(..), boolToRecFlag )
20 import Name              ( Name )
21 import NameEnv
22 import TysWiredIn        ( intTy )
23
24 import Unique
25 import UniqFM
26 import UniqSet
27 import Digraph           ( SCC(..), stronglyConnComp )
28
29 import Outputable
30
31 import Control.Monad  ( liftM2, zipWithM, zipWithM_ )
32
33 -- ----------------------------------------------------------------------------
34 -- Types
35
36 vectTyCon :: TyCon -> VM TyCon
37 vectTyCon tc
38   | isFunTyCon tc        = builtin closureTyCon
39   | isBoxedTupleTyCon tc = return tc
40   | isUnLiftedTyCon tc   = return tc
41   | otherwise = do
42                   r <- lookupTyCon tc
43                   case r of
44                     Just tc' -> return tc'
45
46                     -- FIXME: just for now
47                     Nothing  -> pprTrace "ccTyCon:" (ppr tc) $ return tc
48
49 vectType :: Type -> VM Type
50 vectType ty | Just ty' <- coreView ty = vectType ty'
51 vectType (TyVarTy tv) = return $ TyVarTy tv
52 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
53 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
54 vectType (FunTy ty1 ty2)   = liftM2 TyConApp (builtin closureTyCon)
55                                              (mapM vectType [ty1,ty2])
56 vectType ty@(ForAllTy _ _)
57   = do
58       mdicts   <- mapM paDictArgType tyvars
59       mono_ty' <- vectType mono_ty
60       return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
61   where
62     (tyvars, mono_ty) = splitForAllTys ty
63
64 vectType ty = pprPanic "vectType:" (ppr ty)
65
66 -- ----------------------------------------------------------------------------
67 -- Type definitions
68
69 type TyConGroup = ([TyCon], UniqSet TyCon)
70
71 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [Instance])
72 vectTypeEnv env
73   = do
74       cs <- readGEnv $ mk_map . global_tycons
75       let (conv_tcs, keep_tcs) = classifyTyCons cs groups
76           keep_dcs             = concatMap tyConDataCons keep_tcs
77       zipWithM_ defTyCon   keep_tcs keep_tcs
78       zipWithM_ defDataCon keep_dcs keep_dcs
79       vect_tcs <- vectTyConDecls conv_tcs
80       parr_tcs1 <- zipWithM buildPArrayTyCon keep_tcs keep_tcs
81       parr_tcs2 <- zipWithM buildPArrayTyCon conv_tcs vect_tcs
82       let new_tcs = vect_tcs ++ parr_tcs1 ++ parr_tcs2
83
84       let new_env = extendTypeEnvList env
85                        (map ATyCon new_tcs
86                         ++ [ADataCon dc | tc <- new_tcs
87                                         , dc <- tyConDataCons tc])
88
89       return (new_env, map mkLocalFamInst (parr_tcs1 ++ parr_tcs2), [])
90   where
91     tycons = typeEnvTyCons env
92     groups = tyConGroups tycons
93
94     mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
95
96     keep_tc tc = let dcs = tyConDataCons tc
97                  in
98                  defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
99
100
101 vectTyConDecls :: [TyCon] -> VM [TyCon]
102 vectTyConDecls tcs = fixV $ \tcs' ->
103   do
104     mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
105     mapM vectTyConDecl tcs
106   where
107     lazy_zip [] _ = []
108     lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
109
110 vectTyConDecl :: TyCon -> VM TyCon
111 vectTyConDecl tc
112   = do
113       name' <- cloneName mkVectTyConOcc name
114       rhs'  <- vectAlgTyConRhs (algTyConRhs tc)
115
116       return $ mkAlgTyCon name'
117                           kind
118                           tyvars
119                           []              -- no stupid theta
120                           rhs'
121                           []              -- no selector ids
122                           NoParentTyCon   -- FIXME
123                           rec_flag        -- FIXME: is this ok?
124                           False           -- FIXME: no generics
125                           False           -- not GADT syntax
126   where
127     name   = tyConName tc
128     kind   = tyConKind tc
129     tyvars = tyConTyVars tc
130     rec_flag = boolToRecFlag (isRecursiveTyCon tc)
131
132 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
133 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
134                            , is_enum   = is_enum
135                            })
136   = do
137       data_cons' <- mapM vectDataCon data_cons
138       zipWithM_ defDataCon data_cons data_cons'
139       return $ DataTyCon { data_cons = data_cons'
140                          , is_enum   = is_enum
141                          }
142
143 vectDataCon :: DataCon -> VM DataCon
144 vectDataCon dc
145   | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
146   | not . null $ dataConEqSpec   dc = pprPanic "vectDataCon: eq spec" (ppr dc)
147   | otherwise
148   = do
149       name'    <- cloneName mkVectDataConOcc name
150       tycon'   <- vectTyCon tycon
151       arg_tys  <- mapM vectType rep_arg_tys
152       wrk_name <- cloneName mkDataConWorkerOcc name'
153
154       let ids      = mkDataConIds (panic "vectDataCon: wrapper id")
155                                   wrk_name
156                                   data_con
157           data_con = mkDataCon name'
158                                False           -- not infix
159                                (map (const NotMarkedStrict) arg_tys)
160                                []              -- no labelled fields
161                                univ_tvs
162                                []              -- no existential tvs for now
163                                []              -- no eq spec for now
164                                []              -- no theta
165                                arg_tys
166                                tycon'
167                                []              -- no stupid theta
168                                ids
169       return data_con
170   where
171     name        = dataConName dc
172     univ_tvs    = dataConUnivTyVars dc
173     rep_arg_tys = dataConRepArgTys dc
174     tycon       = dataConTyCon dc
175
176 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
177 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
178   do
179     name'  <- cloneName mkPArrayTyConOcc orig_name
180     parent <- buildPArrayParentInfo orig_name vect_tc repr_tc
181     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
182
183     return $ mkAlgTyCon name'
184                         kind
185                         tyvars
186                         []              -- no stupid theta
187                         rhs
188                         []              -- no selector ids
189                         parent
190                         rec_flag        -- FIXME: is this ok?
191                         False           -- FIXME: no generics
192                         False           -- not GADT syntax
193   where
194     orig_name = tyConName orig_tc
195     name   = tyConName vect_tc
196     kind   = tyConKind vect_tc
197     tyvars = tyConTyVars vect_tc
198     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
199     
200
201 buildPArrayParentInfo :: Name -> TyCon -> TyCon -> VM TyConParent
202 buildPArrayParentInfo orig_name vect_tc repr_tc
203   = do
204       parray_tc <- builtin parrayTyCon
205       co_name <- cloneName mkInstTyCoOcc (tyConName repr_tc)
206
207       let inst_tys = [mkTyConApp vect_tc (map mkTyVarTy tyvars)]
208
209       return . FamilyTyCon parray_tc inst_tys
210              $ mkFamInstCoercion co_name
211                                  tyvars
212                                  parray_tc
213                                  inst_tys
214                                  repr_tc
215   where
216     tyvars = tyConTyVars vect_tc
217
218 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
219 buildPArrayTyConRhs orig_name vect_tc repr_tc
220   = do
221       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
222       return $ DataTyCon { data_cons = [data_con], is_enum = False }
223
224 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
225 buildPArrayDataCon orig_name vect_tc repr_tc
226   = do
227       dc_name  <- cloneName mkPArrayDataConOcc orig_name
228       shape_ty <- mkPArrayType intTy   -- FIXME: we want to unbox this!
229       repr_tys <- mapM mkPArrayType types
230       wrk_name <- cloneName mkDataConWorkerOcc  dc_name
231       wrp_name <- cloneName mkDataConWrapperOcc dc_name
232
233       let ids      = mkDataConIds wrp_name wrk_name data_con
234           data_con = mkDataCon dc_name
235                                False
236                                (MarkedStrict : map (const NotMarkedStrict) repr_tys)
237                                []
238                                (tyConTyVars vect_tc)
239                                []
240                                []
241                                []
242                                (shape_ty : repr_tys)
243                                repr_tc
244                                []
245                                ids
246
247       return data_con
248   where
249     types = [ty | dc <- tyConDataCons vect_tc
250                 , ty <- dataConRepArgTys dc]
251
252 -- | Split the given tycons into two sets depending on whether they have to be
253 -- converted (first list) or not (second list). The first argument contains
254 -- information about the conversion status of external tycons:
255 -- 
256 --   * tycons which have converted versions are mapped to True
257 --   * tycons which are not changed by vectorisation are mapped to False
258 --   * tycons which can't be converted are not elements of the map
259 --
260 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
261 classifyTyCons = classify [] []
262   where
263     classify conv keep cs [] = (conv, keep)
264     classify conv keep cs ((tcs, ds) : rs)
265       | can_convert && must_convert
266         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
267       | can_convert
268         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
269       | otherwise
270         = classify conv keep cs rs
271       where
272         refs = ds `delListFromUniqSet` tcs
273
274         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
275         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
276
277         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
278     
279 -- | Compute mutually recursive groups of tycons in topological order
280 --
281 tyConGroups :: [TyCon] -> [TyConGroup]
282 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
283   where
284     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
285                                 , let ds = tyConsOfTyCon tc]
286
287     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
288     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
289       where
290         (tcs, dss) = unzip els
291
292 tyConsOfTyCon :: TyCon -> UniqSet TyCon
293 tyConsOfTyCon 
294   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
295
296 tyConsOfType :: Type -> UniqSet TyCon
297 tyConsOfType ty
298   | Just ty' <- coreView ty    = tyConsOfType ty'
299 tyConsOfType (TyVarTy v)       = emptyUniqSet
300 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
301   where
302     extend | isUnLiftedTyCon tc
303            || isTupleTyCon   tc = id
304
305            | otherwise          = (`addOneToUniqSet` tc)
306
307 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
308 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
309                                  `addOneToUniqSet` funTyCon
310 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
311 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
312
313 tyConsOfTypes :: [Type] -> UniqSet TyCon
314 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
315