Modify generation of PR dictionaries for new scheme
[ghc-hetmet.git] / compiler / vectorise / VectType.hs
1 module VectType ( vectTyCon, vectType, vectTypeEnv,
2                    PAInstance, buildPADict )
3 where
4
5 #include "HsVersions.h"
6
7 import VectMonad
8 import VectUtils
9 import VectCore
10
11 import HscTypes          ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
12 import CoreSyn
13 import CoreUtils
14 import BuildTyCl
15 import DataCon
16 import TyCon
17 import Type
18 import TypeRep
19 import Coercion
20 import FamInstEnv        ( FamInst, mkLocalFamInst )
21 import InstEnv           ( Instance, mkLocalInstance, instanceDFunId )
22 import OccName
23 import MkId
24 import BasicTypes        ( StrictnessMark(..), OverlapFlag(..), boolToRecFlag )
25 import Var               ( Var )
26 import Id                ( mkWildId )
27 import Name              ( Name, getOccName )
28 import NameEnv
29 import TysWiredIn        ( unitTy, unitTyCon, intTy, intDataCon, unitDataConId )
30 import TysPrim           ( intPrimTy )
31
32 import Unique
33 import UniqFM
34 import UniqSet
35 import Digraph           ( SCC(..), stronglyConnComp )
36
37 import Outputable
38
39 import Control.Monad  ( liftM, liftM2, zipWithM, zipWithM_ )
40 import Data.List      ( inits, tails, zipWith4, zipWith5 )
41
42 -- ----------------------------------------------------------------------------
43 -- Types
44
45 vectTyCon :: TyCon -> VM TyCon
46 vectTyCon tc
47   | isFunTyCon tc        = builtin closureTyCon
48   | isBoxedTupleTyCon tc = return tc
49   | isUnLiftedTyCon tc   = return tc
50   | otherwise = do
51                   r <- lookupTyCon tc
52                   case r of
53                     Just tc' -> return tc'
54
55                     -- FIXME: just for now
56                     Nothing  -> pprTrace "ccTyCon:" (ppr tc) $ return tc
57
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 _ _)
66   = do
67       mdicts   <- mapM paDictArgType tyvars
68       mono_ty' <- vectType mono_ty
69       return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
70   where
71     (tyvars, mono_ty) = splitForAllTys ty
72
73 vectType ty = pprPanic "vectType:" (ppr ty)
74
75 -- ----------------------------------------------------------------------------
76 -- Type definitions
77
78 type TyConGroup = ([TyCon], UniqSet TyCon)
79
80 data PAInstance = PAInstance {
81                     painstDFun      :: Var
82                   , painstOrigTyCon :: TyCon
83                   , painstVectTyCon :: TyCon
84                   , painstArrTyCon  :: TyCon
85                   }
86
87 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [(Var, CoreExpr)])
88 vectTypeEnv env
89   = do
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
96
97       let orig_tcs = keep_tcs ++ conv_tcs
98           vect_tcs  = keep_tcs ++ new_tcs
99
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 (zipWith5 buildTyConBindings orig_tcs
105                                                         vect_tcs
106                                                         repr_tcs
107                                                         parr_tcs
108                                                         dfuns)
109
110       let all_new_tcs = new_tcs ++ repr_tcs ++ parr_tcs
111
112       let new_env = extendTypeEnvList env
113                        (map ATyCon all_new_tcs
114                         ++ [ADataCon dc | tc <- all_new_tcs
115                                         , dc <- tyConDataCons tc])
116
117       return (new_env, map mkLocalFamInst (repr_tcs ++ parr_tcs), concat binds)
118   where
119     tycons = typeEnvTyCons env
120     groups = tyConGroups tycons
121
122     mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
123
124     keep_tc tc = let dcs = tyConDataCons tc
125                  in
126                  defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
127
128
129 vectTyConDecls :: [TyCon] -> VM [TyCon]
130 vectTyConDecls tcs = fixV $ \tcs' ->
131   do
132     mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
133     mapM vectTyConDecl tcs
134   where
135     lazy_zip [] _ = []
136     lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
137
138 vectTyConDecl :: TyCon -> VM TyCon
139 vectTyConDecl tc
140   = do
141       name' <- cloneName mkVectTyConOcc name
142       rhs'  <- vectAlgTyConRhs (algTyConRhs tc)
143
144       liftDs $ buildAlgTyCon name'
145                              tyvars
146                              []           -- no stupid theta
147                              rhs'
148                              rec_flag     -- FIXME: is this ok?
149                              False        -- FIXME: no generics
150                              False        -- not GADT syntax
151                              Nothing      -- not a family instance
152   where
153     name   = tyConName tc
154     tyvars = tyConTyVars tc
155     rec_flag = boolToRecFlag (isRecursiveTyCon tc)
156
157 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
158 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
159                            , is_enum   = is_enum
160                            })
161   = do
162       data_cons' <- mapM vectDataCon data_cons
163       zipWithM_ defDataCon data_cons data_cons'
164       return $ DataTyCon { data_cons = data_cons'
165                          , is_enum   = is_enum
166                          }
167
168 vectDataCon :: DataCon -> VM DataCon
169 vectDataCon dc
170   | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
171   | not . null $ dataConEqSpec   dc = pprPanic "vectDataCon: eq spec" (ppr dc)
172   | otherwise
173   = do
174       name'    <- cloneName mkVectDataConOcc name
175       tycon'   <- vectTyCon tycon
176       arg_tys  <- mapM vectType rep_arg_tys
177
178       liftDs $ buildDataCon name'
179                             False           -- not infix
180                             (map (const NotMarkedStrict) arg_tys)
181                             []              -- no labelled fields
182                             univ_tvs
183                             []              -- no existential tvs for now
184                             []              -- no eq spec for now
185                             []              -- no context
186                             arg_tys
187                             tycon'
188   where
189     name        = dataConName dc
190     univ_tvs    = dataConUnivTyVars dc
191     rep_arg_tys = dataConRepArgTys dc
192     tycon       = dataConTyCon dc
193
194 mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
195 mk_fam_inst fam_tc arg_tc
196   = (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
197
198 buildPReprTyCon :: TyCon -> TyCon -> VM TyCon
199 buildPReprTyCon orig_tc vect_tc
200   = do
201       name     <- cloneName mkPReprTyConOcc (tyConName orig_tc)
202       rhs_ty   <- buildPReprType vect_tc
203       prepr_tc <- builtin preprTyCon
204       liftDs $ buildSynTyCon name
205                              tyvars
206                              (SynonymTyCon rhs_ty)
207                              (Just $ mk_fam_inst prepr_tc vect_tc)
208   where
209     tyvars = tyConTyVars vect_tc
210
211 buildPReprType :: TyCon -> VM Type
212 buildPReprType = liftM repr_type . mkTyConRepr
213
214 buildToPRepr :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
215 buildToPRepr (TyConRepr {
216                 repr_tys            = repr_tys
217               , repr_prod_data_cons = prod_data_cons
218               , repr_prod_tys       = prod_tys
219               , repr_sum_data_cons  = sum_data_cons
220               , repr_type           = repr_type
221               })
222               vect_tc prepr_tc _
223   = do
224       arg  <- newLocalVar FSLIT("x") arg_ty
225       vars <- mapM (mapM (newLocalVar FSLIT("x"))) repr_tys
226
227       return . Lam arg
228              . wrapFamInstBody prepr_tc var_tys
229              . Case (Var arg) (mkWildId arg_ty) repr_type
230              . mk_alts data_cons vars
231              . zipWith3 mk_prod prod_data_cons repr_tys $ map (map Var) vars
232   where
233     var_tys   = mkTyVarTys $ tyConTyVars vect_tc
234     arg_ty    = mkTyConApp vect_tc var_tys
235     data_cons = tyConDataCons vect_tc
236
237     mk_alts _    _      []     = [(DEFAULT, [], Var unitDataConId)]
238     mk_alts [dc] [vars] [expr] = [(DataAlt dc, vars, expr)]
239     mk_alts dcs  vars   exprs  = zipWith4 mk_alt dcs vars sum_data_cons exprs 
240
241     mk_alt dc vars sum_dc expr = (DataAlt dc, vars,
242                                   mkConApp sum_dc (map Type prod_tys ++ [expr]))
243
244     mk_prod _         _   []     = Var unitDataConId
245     mk_prod _         _   [expr] = expr
246     mk_prod (Just dc) tys exprs  = mkConApp dc (map Type tys ++ exprs)
247
248 buildFromPRepr :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
249 buildFromPRepr (TyConRepr {
250                 repr_tys            = repr_tys
251               , repr_prod_data_cons = prod_data_cons
252               , repr_prod_tys       = prod_tys
253               , repr_sum_data_cons  = sum_data_cons
254               , repr_type           = repr_type
255               })
256               vect_tc prepr_tc _
257   = do
258       arg_ty <- mkPReprType res_ty
259       arg    <- newLocalVar FSLIT("x") arg_ty
260
261       liftM (Lam arg
262              . un_sum (unwrapFamInstScrut prepr_tc var_tys (Var arg)))
263             (sequence
264              $ zipWith4 un_prod data_cons prod_data_cons prod_tys repr_tys)
265   where
266     var_tys   = mkTyVarTys $ tyConTyVars vect_tc
267     ty_args   = map Type var_tys
268     res_ty    = mkTyConApp vect_tc var_tys
269     data_cons = tyConDataCons vect_tc
270
271     un_prod dc _ _ []
272       = do
273           var <- newLocalVar FSLIT("u") unitTy
274           return (var, mkConApp dc ty_args)
275     un_prod dc _ _ [ty]
276       = do
277           var <- newLocalVar FSLIT("x") ty
278           return (var, mkConApp dc (ty_args ++ [Var var]))
279
280     un_prod dc (Just prod_dc) prod_ty tys
281       = do
282           vars  <- mapM (newLocalVar FSLIT("x")) tys
283           pv    <- newLocalVar FSLIT("p") prod_ty
284
285           let res  = mkConApp dc (ty_args ++ map Var vars)
286               expr = Case (Var pv) (mkWildId prod_ty) res_ty
287                         [(DataAlt prod_dc, vars, res)]
288
289           return (pv, expr)
290
291     un_sum scrut [(var, expr)] = Let (NonRec var scrut) expr
292     un_sum scrut alts
293       = Case scrut (mkWildId repr_type) res_ty
294       $ zipWith mk_alt sum_data_cons alts
295
296     mk_alt sum_dc (var, expr) = (DataAlt sum_dc, [var], expr)
297
298
299 buildToArrPRepr :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
300 buildToArrPRepr _ vect_tc prepr_tc arr_tc
301   = do
302       arg_ty  <- mkPArrayType el_ty
303       rep_tys <- mapM (mapM mkPArrayType) rep_el_tys
304
305       arg     <- newLocalVar FSLIT("xs") arg_ty
306       bndrss  <- mapM (mapM (newLocalVar FSLIT("ys"))) rep_tys
307       len     <- newLocalVar FSLIT("len") intPrimTy
308       sel     <- newLocalVar FSLIT("sel") =<< mkPArrayType intTy
309
310       let add_sel xs | has_selector = sel : xs
311                      | otherwise    = xs
312
313           all_bndrs = len : add_sel (concat bndrss)
314
315       res      <- parrayCoerce prepr_tc var_tys
316                 =<< mkToArrPRepr (Var len) (Var sel) (map (map Var) bndrss)
317       res_ty   <- mkPArrayType =<< mkPReprType el_ty
318
319       return . Lam arg
320              $ Case (unwrapFamInstScrut arr_tc var_tys (Var arg))
321                     (mkWildId (mkTyConApp arr_tc var_tys))
322                     res_ty
323                     [(DataAlt arr_dc, all_bndrs, res)]
324   where
325     var_tys    = mkTyVarTys $ tyConTyVars vect_tc
326     el_ty      = mkTyConApp vect_tc var_tys
327     data_cons  = tyConDataCons vect_tc
328     rep_el_tys = map dataConRepArgTys data_cons
329
330     [arr_dc]   = tyConDataCons arr_tc
331
332     has_selector | [_] <- data_cons = False
333                  | otherwise        = True
334
335 buildFromArrPRepr :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
336 buildFromArrPRepr _ vect_tc prepr_tc arr_tc
337   = mkFromArrPRepr undefined undefined undefined undefined undefined undefined
338
339 buildPRDict :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
340 buildPRDict (TyConRepr {
341                 repr_tys         = repr_tys
342               , repr_prod_tycons = prod_tycons
343               , repr_prod_tys    = prod_tys
344               , repr_sum_tycon   = repr_sum_tycon
345               })
346             vect_tc prepr_tc _
347   = do
348       prs      <- mapM (mapM mkPR) repr_tys
349       prod_prs <- sequence $ zipWith3 mk_prod_pr prod_tycons repr_tys prs
350       sum_pr   <- mk_sum_pr prod_prs
351       prCoerce prepr_tc var_tys sum_pr
352   where
353     var_tys = mkTyVarTys $ tyConTyVars vect_tc
354
355     Just sum_tycon = repr_sum_tycon
356
357     mk_prod_pr _         _   []   = prDFunOfTyCon unitTyCon
358     mk_prod_pr _         _   [pr] = return pr
359     mk_prod_pr (Just tc) tys prs
360       = do
361           dfun <- prDFunOfTyCon tc
362           return $ dfun `mkTyApps` tys `mkApps` prs
363
364     mk_sum_pr [pr] = return pr
365     mk_sum_pr prs
366       = do
367           dfun <- prDFunOfTyCon sum_tycon
368           return $ dfun `mkTyApps` prod_tys `mkApps` prs
369
370 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
371 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
372   do
373     name'  <- cloneName mkPArrayTyConOcc orig_name
374     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
375     parray <- builtin parrayTyCon
376
377     liftDs $ buildAlgTyCon name'
378                            tyvars
379                            []          -- no stupid theta
380                            rhs
381                            rec_flag    -- FIXME: is this ok?
382                            False       -- FIXME: no generics
383                            False       -- not GADT syntax
384                            (Just $ mk_fam_inst parray vect_tc)
385   where
386     orig_name = tyConName orig_tc
387     tyvars = tyConTyVars vect_tc
388     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
389     
390
391 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
392 buildPArrayTyConRhs orig_name vect_tc repr_tc
393   = do
394       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
395       return $ DataTyCon { data_cons = [data_con], is_enum = False }
396
397 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
398 buildPArrayDataCon orig_name vect_tc repr_tc
399   = do
400       dc_name  <- cloneName mkPArrayDataConOcc orig_name
401       shape    <- tyConShape vect_tc
402       repr_tys <- mapM mkPArrayType types
403
404       liftDs $ buildDataCon dc_name
405                             False                  -- not infix
406                             (shapeStrictness shape ++ map (const NotMarkedStrict) repr_tys)
407                             []                     -- no field labels
408                             (tyConTyVars vect_tc)
409                             []                     -- no existentials
410                             []                     -- no eq spec
411                             []                     -- no context
412                             (shapeReprTys shape ++ repr_tys)
413                             repr_tc
414   where
415     types = [ty | dc <- tyConDataCons vect_tc
416                 , ty <- dataConRepArgTys dc]
417
418 mkPADFun :: TyCon -> VM Var
419 mkPADFun vect_tc
420   = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
421
422 data Shape = Shape {
423                shapeReprTys    :: [Type]
424              , shapeStrictness :: [StrictnessMark]
425              , shapeLength     :: [CoreExpr] -> VM CoreExpr
426              , shapeReplicate  :: CoreExpr -> CoreExpr -> VM [CoreExpr]
427              }
428
429 tyConShape :: TyCon -> VM Shape
430 tyConShape vect_tc
431   | isProductTyCon vect_tc
432   = return $ Shape {
433                 shapeReprTys    = [intPrimTy]
434               , shapeStrictness = [NotMarkedStrict]
435               , shapeLength     = \[len] -> return len
436               , shapeReplicate  = \len _ -> return [len]
437               }
438
439   | otherwise
440   = do
441       repr_ty <- mkPArrayType intTy   -- FIXME: we want to unbox this
442       return $ Shape {
443                  shapeReprTys    = [repr_ty]
444                , shapeStrictness = [MarkedStrict]
445                , shapeLength     = \[sel] -> lengthPA sel
446                , shapeReplicate  = \len n -> do
447                                                e <- replicatePA len n
448                                                return [e]
449                }
450
451 buildTyConBindings :: TyCon -> TyCon -> TyCon -> TyCon -> Var
452                    -> VM [(Var, CoreExpr)]
453 buildTyConBindings orig_tc vect_tc prepr_tc arr_tc dfun
454   = do
455       shape <- tyConShape vect_tc
456       repr  <- mkTyConRepr vect_tc
457       sequence_ (zipWith4 (vectDataConWorker shape vect_tc arr_tc arr_dc)
458                           orig_dcs
459                           vect_dcs
460                           (inits repr_tys)
461                           (tails repr_tys))
462       dict <- buildPADict repr vect_tc prepr_tc arr_tc dfun
463       binds <- takeHoisted
464       return $ (dfun, dict) : binds
465   where
466     orig_dcs = tyConDataCons orig_tc
467     vect_dcs = tyConDataCons vect_tc
468     [arr_dc] = tyConDataCons arr_tc
469
470     repr_tys = map dataConRepArgTys vect_dcs
471
472 vectDataConWorker :: Shape -> TyCon -> TyCon -> DataCon
473                   -> DataCon -> DataCon -> [[Type]] -> [[Type]]
474                   -> VM ()
475 vectDataConWorker shape vect_tc arr_tc arr_dc orig_dc vect_dc pre (dc_tys : post)
476   = do
477       clo <- closedV
478            . inBind orig_worker
479            . polyAbstract tvs $ \abstract ->
480              liftM (abstract . vectorised)
481            $ buildClosures tvs [] dc_tys res_ty (liftM2 (,) mk_vect mk_lift)
482
483       worker <- cloneId mkVectOcc orig_worker (exprType clo)
484       hoistBinding worker clo
485       defGlobalVar orig_worker worker
486       return ()
487   where
488     tvs     = tyConTyVars vect_tc
489     arg_tys = mkTyVarTys tvs
490     res_ty  = mkTyConApp vect_tc arg_tys
491
492     orig_worker = dataConWorkId orig_dc
493
494     mk_vect = return . mkConApp vect_dc $ map Type arg_tys
495     mk_lift = do
496                 len     <- newLocalVar FSLIT("n") intPrimTy
497                 arr_tys <- mapM mkPArrayType dc_tys
498                 args    <- mapM (newLocalVar FSLIT("xs")) arr_tys
499                 shapes  <- shapeReplicate shape
500                                           (Var len)
501                                           (mkDataConTag vect_dc)
502                 
503                 empty_pre  <- mapM emptyPA (concat pre)
504                 empty_post <- mapM emptyPA (concat post)
505
506                 return . mkLams (len : args)
507                        . wrapFamInstBody arr_tc arg_tys
508                        . mkConApp arr_dc
509                        $ map Type arg_tys ++ shapes
510                                           ++ empty_pre
511                                           ++ map Var args
512                                           ++ empty_post
513
514 buildPADict :: TyConRepr -> TyCon -> TyCon -> TyCon -> Var -> VM CoreExpr
515 buildPADict repr vect_tc prepr_tc arr_tc dfun
516   = polyAbstract tvs $ \abstract ->
517     do
518       meth_binds <- mapM (mk_method repr) paMethods
519       let meth_exprs = map (Var . fst) meth_binds
520
521       pa_dc <- builtin paDataCon
522       let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
523           body = Let (Rec meth_binds) dict
524       return . mkInlineMe $ abstract body
525   where
526     tvs = tyConTyVars arr_tc
527     arg_tys = mkTyVarTys tvs
528
529     mk_method repr (name, build)
530       = localV
531       $ do
532           body <- build repr vect_tc prepr_tc arr_tc
533           var  <- newLocalVar name (exprType body)
534           return (var, mkInlineMe body)
535           
536 paMethods = [(FSLIT("toPRepr"),      buildToPRepr),
537              (FSLIT("fromPRepr"),    buildFromPRepr),
538              (FSLIT("toArrPRepr"),   buildToArrPRepr),
539              (FSLIT("fromArrPRepr"), buildFromArrPRepr),
540              (FSLIT("dictPRepr"),    buildPRDict)]
541
542 -- | Split the given tycons into two sets depending on whether they have to be
543 -- converted (first list) or not (second list). The first argument contains
544 -- information about the conversion status of external tycons:
545 -- 
546 --   * tycons which have converted versions are mapped to True
547 --   * tycons which are not changed by vectorisation are mapped to False
548 --   * tycons which can't be converted are not elements of the map
549 --
550 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
551 classifyTyCons = classify [] []
552   where
553     classify conv keep cs [] = (conv, keep)
554     classify conv keep cs ((tcs, ds) : rs)
555       | can_convert && must_convert
556         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
557       | can_convert
558         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
559       | otherwise
560         = classify conv keep cs rs
561       where
562         refs = ds `delListFromUniqSet` tcs
563
564         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
565         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
566
567         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
568     
569 -- | Compute mutually recursive groups of tycons in topological order
570 --
571 tyConGroups :: [TyCon] -> [TyConGroup]
572 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
573   where
574     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
575                                 , let ds = tyConsOfTyCon tc]
576
577     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
578     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
579       where
580         (tcs, dss) = unzip els
581
582 tyConsOfTyCon :: TyCon -> UniqSet TyCon
583 tyConsOfTyCon 
584   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
585
586 tyConsOfType :: Type -> UniqSet TyCon
587 tyConsOfType ty
588   | Just ty' <- coreView ty    = tyConsOfType ty'
589 tyConsOfType (TyVarTy v)       = emptyUniqSet
590 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
591   where
592     extend | isUnLiftedTyCon tc
593            || isTupleTyCon   tc = id
594
595            | otherwise          = (`addOneToUniqSet` tc)
596
597 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
598 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
599                                  `addOneToUniqSet` funTyCon
600 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
601 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
602
603 tyConsOfTypes :: [Type] -> UniqSet TyCon
604 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
605