VectUtils.hs 14.2 KB
Newer Older
1
module VectUtils (
2
  collectAnnTypeBinders, collectAnnTypeArgs, isAnnTypeArg,
3
  collectAnnValBinders,
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
4
5
6
  dataConTagZ, mkDataConTag, mkDataConTagLit,

  newLocalVVar,
7

8
  mkBuiltinCo,
9
  mkPADictType, mkPArrayType, mkPReprType,
10

11
12
  parrayReprTyCon, parrayReprDataCon, mkVScrut,
  prDFunOfTyCon,
13
  paDictArgType, paDictOfType, paDFunType,
14
  paMethod, mkPR, lengthPA, replicatePA, emptyPA, packPA, combinePA, liftPA,
15
  polyAbstract, polyApply, polyVApply,
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
16
  hoistBinding, hoistExpr, hoistPolyVExpr, takeHoisted,
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
17
18
  buildClosure, buildClosures,
  mkClosureApp
19
20
21
22
) where

#include "HsVersions.h"

23
import VectCore
24
25
import VectMonad

26
import DsUtils
27
import CoreSyn
28
import CoreUtils
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
29
import Coercion
30
31
import Type
import TypeRep
32
import TyCon
33
import DataCon
34
import Var
35
36
37
38
import Id                 ( mkWildId )
import MkId               ( unwrapFamInstScrut )
import TysWiredIn
import BasicTypes         ( Boxity(..) )
39
import Literal            ( Literal, mkMachInt )
40

41
import Outputable
42
import FastString
43

twanvl's avatar
twanvl committed
44
45
import Control.Monad

46

47
48
49
50
51
52
53
54
55
56
57
58
collectAnnTypeArgs :: AnnExpr b ann -> (AnnExpr b ann, [Type])
collectAnnTypeArgs expr = go expr []
  where
    go (_, AnnApp f (_, AnnType ty)) tys = go f (ty : tys)
    go e                             tys = (e, tys)

collectAnnTypeBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
collectAnnTypeBinders expr = go [] expr
  where
    go bs (_, AnnLam b e) | isTyVar b = go (b:bs) e
    go bs e                           = (reverse bs, e)

59
60
61
62
63
64
collectAnnValBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
collectAnnValBinders expr = go [] expr
  where
    go bs (_, AnnLam b e) | isId b = go (b:bs) e
    go bs e                        = (reverse bs, e)

65
isAnnTypeArg :: AnnExpr b ann -> Bool
twanvl's avatar
twanvl committed
66
isAnnTypeArg (_, AnnType _) = True
67
68
isAnnTypeArg _              = False

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
69
70
71
dataConTagZ :: DataCon -> Int
dataConTagZ con = dataConTag con - fIRST_TAG

72
mkDataConTagLit :: DataCon -> Literal
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
73
mkDataConTagLit = mkMachInt . toInteger . dataConTagZ
74

75
mkDataConTag :: DataCon -> CoreExpr
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
76
mkDataConTag = mkIntLitInt . dataConTagZ
77

78
79
80
81
82
83
84
85
splitPrimTyCon :: Type -> Maybe TyCon
splitPrimTyCon ty
  | Just (tycon, []) <- splitTyConApp_maybe ty
  , isPrimTyCon tycon
  = Just tycon

  | otherwise = Nothing

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
86
87
mkBuiltinTyConApp :: (Builtins -> TyCon) -> [Type] -> VM Type
mkBuiltinTyConApp get_tc tys
88
  = do
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
89
90
      tc <- builtin get_tc
      return $ mkTyConApp tc tys
91

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
92
93
mkBuiltinTyConApps :: (Builtins -> TyCon) -> [Type] -> Type -> VM Type
mkBuiltinTyConApps get_tc tys ty
94
  = do
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
95
96
      tc <- builtin get_tc
      return $ foldr (mk tc) ty tys
97
  where
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
98
    mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2]
99

twanvl's avatar
twanvl committed
100
{-
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
101
mkBuiltinTyConApps1 :: (Builtins -> TyCon) -> Type -> [Type] -> VM Type
twanvl's avatar
twanvl committed
102
103
mkBuiltinTyConApps1 _      dft [] = return dft
mkBuiltinTyConApps1 get_tc _   tys
104
  = do
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
105
106
107
108
109
110
111
112
113
      tc <- builtin get_tc
      case tys of
        [] -> pprPanic "mkBuiltinTyConApps1" (ppr tc)
        _  -> return $ foldr1 (mk tc) tys
  where
    mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2]

mkClosureType :: Type -> Type -> VM Type
mkClosureType arg_ty res_ty = mkBuiltinTyConApp closureTyCon [arg_ty, res_ty]
twanvl's avatar
twanvl committed
114
-}
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
115
116
117
118

mkClosureTypes :: [Type] -> Type -> VM Type
mkClosureTypes = mkBuiltinTyConApps closureTyCon

119
120
121
mkPReprType :: Type -> VM Type
mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty]

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
122
123
mkPADictType :: Type -> VM Type
mkPADictType ty = mkBuiltinTyConApp paTyCon [ty]
124
125

mkPArrayType :: Type -> VM Type
126
127
128
129
130
131
mkPArrayType ty
  | Just tycon <- splitPrimTyCon ty
  = do
      arr <- traceMaybeV "mkPArrayType" (ppr tycon)
           $ lookupPrimPArray tycon
      return $ mkTyConApp arr []
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
132
mkPArrayType ty = mkBuiltinTyConApp parrayTyCon [ty]
133

134
135
mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion
mkBuiltinCo get_tc
136
  = do
137
138
      tc <- builtin get_tc
      return $ mkTyConApp tc []
139

140
141
142
143
144
145
146
147
148
149
parrayReprTyCon :: Type -> VM (TyCon, [Type])
parrayReprTyCon ty = builtin parrayTyCon >>= (`lookupFamInst` [ty])

parrayReprDataCon :: Type -> VM (DataCon, [Type])
parrayReprDataCon ty
  = do
      (tc, arg_tys) <- parrayReprTyCon ty
      let [dc] = tyConDataCons tc
      return (dc, arg_tys)

150
151
152
153
154
155
mkVScrut :: VExpr -> VM (VExpr, TyCon, [Type])
mkVScrut (ve, le)
  = do
      (tc, arg_tys) <- parrayReprTyCon (exprType ve)
      return ((ve, unwrapFamInstScrut tc arg_tys le), tc, arg_tys)

156
157
158
prDFunOfTyCon :: TyCon -> VM CoreExpr
prDFunOfTyCon tycon
  = liftM Var (traceMaybeV "prDictOfTyCon" (ppr tycon) (lookupTyConPR tycon))
159

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
paDictArgType :: TyVar -> VM (Maybe Type)
paDictArgType tv = go (TyVarTy tv) (tyVarKind tv)
  where
    go ty k | Just k' <- kindView k = go ty k'
    go ty (FunTy k1 k2)
      = do
          tv   <- newTyVar FSLIT("a") k1
          mty1 <- go (TyVarTy tv) k1
          case mty1 of
            Just ty1 -> do
                          mty2 <- go (AppTy ty (TyVarTy tv)) k2
                          return $ fmap (ForAllTy tv . FunTy ty1) mty2
            Nothing  -> go ty k2

    go ty k
      | isLiftedTypeKind k
176
      = liftM Just (mkPADictType ty)
177

twanvl's avatar
twanvl committed
178
    go _ _ = return Nothing
179

180
181
182
183
184
185
186
187
188
189
190
191
192
193
paDictOfType :: Type -> VM CoreExpr
paDictOfType ty = paDictOfTyApp ty_fn ty_args
  where
    (ty_fn, ty_args) = splitAppTys ty

paDictOfTyApp :: Type -> [Type] -> VM CoreExpr
paDictOfTyApp ty_fn ty_args
  | Just ty_fn' <- coreView ty_fn = paDictOfTyApp ty_fn' ty_args
paDictOfTyApp (TyVarTy tv) ty_args
  = do
      dfun <- maybeV (lookupTyVarPA tv)
      paDFunApply dfun ty_args
paDictOfTyApp (TyConApp tc _) ty_args
  = do
194
      dfun <- traceMaybeV "paDictOfTyApp" (ppr tc) (lookupTyConPA tc)
195
      paDFunApply (Var dfun) ty_args
twanvl's avatar
twanvl committed
196
paDictOfTyApp ty _ = pprPanic "paDictOfTyApp" (ppr ty)
197

198
199
200
201
202
203
204
205
206
207
208
paDFunType :: TyCon -> VM Type
paDFunType tc
  = do
      margs <- mapM paDictArgType tvs
      res   <- mkPADictType (mkTyConApp tc arg_tys)
      return . mkForAllTys tvs
             $ mkFunTys [arg | Just arg <- margs] res
  where
    tvs = tyConTyVars tc
    arg_tys = mkTyVarTys tvs

209
210
211
212
213
214
paDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
paDFunApply dfun tys
  = do
      dicts <- mapM paDictOfType tys
      return $ mkApps (mkTyApps dfun tys) dicts

215
216
type PAMethod = (Builtins -> Var, String)

twanvl's avatar
twanvl committed
217
pa_length, pa_replicate, pa_empty, pa_pack :: (Builtins -> Var, String)
218
219
220
pa_length    = (lengthPAVar,    "lengthPA")
pa_replicate = (replicatePAVar, "replicatePA")
pa_empty     = (emptyPAVar,     "emptyPA")
221
pa_pack      = (packPAVar,      "packPA")
222
223

paMethod :: PAMethod -> Type -> VM CoreExpr
twanvl's avatar
twanvl committed
224
paMethod (_method, name) ty
225
  | Just tycon <- splitPrimTyCon ty
226
227
228
229
230
  = do
      fn <- traceMaybeV "paMethod" (ppr tycon <+> text name)
          $ lookupPrimMethod tycon name
      return (Var fn)

twanvl's avatar
twanvl committed
231
paMethod (method, _name) ty
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
232
233
234
235
236
  = do
      fn   <- builtin method
      dict <- paDictOfType ty
      return $ mkApps (Var fn) [Type ty, dict]

237
mkPR :: Type -> VM CoreExpr
238
239
240
241
242
mkPR ty
  = do
      fn   <- builtin mkPRVar
      dict <- paDictOfType ty
      return $ mkApps (Var fn) [Type ty, dict]
243

244
245
lengthPA :: Type -> CoreExpr -> VM CoreExpr
lengthPA ty x = liftM (`App` x) (paMethod pa_length ty)
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
246
247
248

replicatePA :: CoreExpr -> CoreExpr -> VM CoreExpr
replicatePA len x = liftM (`mkApps` [len,x])
249
                          (paMethod pa_replicate (exprType x))
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
250

251
emptyPA :: Type -> VM CoreExpr
252
emptyPA = paMethod pa_empty
253

254
packPA :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> VM CoreExpr
255
packPA ty xs len sel = liftM (`mkApps` [xs, len, sel])
256
257
                             (paMethod pa_pack ty)

258
259
260
261
262
263
264
265
combinePA :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> [CoreExpr]
          -> VM CoreExpr
combinePA ty len sel is xs
  = liftM (`mkApps` (len : sel : is : xs))
          (paMethod (combinePAVar n, "combine" ++ show n ++ "PA") ty)
  where
    n = length xs

266
267
268
269
270
271
liftPA :: CoreExpr -> VM CoreExpr
liftPA x
  = do
      lc <- builtin liftingContext
      replicatePA (Var lc) x

272
273
274
275
276
277
278
279
newLocalVVar :: FastString -> Type -> VM VVar
newLocalVVar fs vty
  = do
      lty <- mkPArrayType vty
      vv  <- newLocalVar fs vty
      lv  <- newLocalVar fs lty
      return (vv,lv)

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
280
281
282
283
polyAbstract :: [TyVar] -> ((CoreExpr -> CoreExpr) -> VM a) -> VM a
polyAbstract tvs p
  = localV
  $ do
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
284
285
286
287
288
289
290
291
292
293
294
295
      mdicts <- mapM mk_dict_var tvs
      zipWithM_ (\tv -> maybe (defLocalTyVar tv) (defLocalTyVarWithPA tv . Var)) tvs mdicts
      p (mk_lams mdicts)
  where
    mk_dict_var tv = do
                       r <- paDictArgType tv
                       case r of
                         Just ty -> liftM Just (newLocalVar FSLIT("dPA") ty)
                         Nothing -> return Nothing

    mk_lams mdicts = mkLams (tvs ++ [dict | Just dict <- mdicts])

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
296
297
polyApply :: CoreExpr -> [Type] -> VM CoreExpr
polyApply expr tys
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
298
299
300
301
  = do
      dicts <- mapM paDictOfType tys
      return $ expr `mkTyApps` tys `mkApps` dicts

302
303
304
305
306
307
polyVApply :: VExpr -> [Type] -> VM VExpr
polyVApply expr tys
  = do
      dicts <- mapM paDictOfType tys
      return $ mapVect (\e -> e `mkTyApps` tys `mkApps` dicts) expr

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
308
309
310
311
hoistBinding :: Var -> CoreExpr -> VM ()
hoistBinding v e = updGEnv $ \env ->
  env { global_bindings = (v,e) : global_bindings env }

312
313
314
315
hoistExpr :: FastString -> CoreExpr -> VM Var
hoistExpr fs expr
  = do
      var <- newLocalVar fs (exprType expr)
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
316
      hoistBinding var expr
317
318
      return var

319
320
hoistVExpr :: VExpr -> VM VVar
hoistVExpr (ve, le)
321
  = do
322
      fs <- getBindName
323
324
325
      vv <- hoistExpr ('v' `consFS` fs) ve
      lv <- hoistExpr ('l' `consFS` fs) le
      return (vv, lv)
326

327
328
hoistPolyVExpr :: [TyVar] -> VM VExpr -> VM VExpr
hoistPolyVExpr tvs p
329
  = do
330
331
      expr <- closedV . polyAbstract tvs $ \abstract ->
              liftM (mapVect abstract) p
332
      fn   <- hoistVExpr expr
333
      polyVApply (vVar fn) (mkTyVarTys tvs)
334

335
336
337
338
339
340
341
takeHoisted :: VM [(Var, CoreExpr)]
takeHoisted
  = do
      env <- readGEnv id
      setGEnv $ env { global_bindings = [] }
      return $ global_bindings env

twanvl's avatar
twanvl committed
342
{-
343
344
345
346
347
348
349
350
351
352
353
boxExpr :: Type -> VExpr -> VM VExpr
boxExpr ty (vexpr, lexpr)
  | Just (tycon, []) <- splitTyConApp_maybe ty
  , isUnLiftedTyCon tycon
  = do
      r <- lookupBoxedTyCon tycon
      case r of
        Just tycon' -> let [dc] = tyConDataCons tycon'
                       in
                       return (mkConApp dc [vexpr], lexpr)
        Nothing     -> return (vexpr, lexpr)
twanvl's avatar
twanvl committed
354
-}
355

356
357
mkClosure :: Type -> Type -> Type -> VExpr -> VExpr -> VM VExpr
mkClosure arg_ty res_ty env_ty (vfn,lfn) (venv,lenv)
358
  = do
359
360
361
362
363
      dict <- paDictOfType env_ty
      mkv  <- builtin mkClosureVar
      mkl  <- builtin mkClosurePVar
      return (Var mkv `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, venv],
              Var mkl `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, lenv])
364

365
366
mkClosureApp :: Type -> Type -> VExpr -> VExpr -> VM VExpr
mkClosureApp arg_ty res_ty (vclo, lclo) (varg, larg)
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
367
368
369
370
371
372
  = do
      vapply <- builtin applyClosureVar
      lapply <- builtin applyClosurePVar
      return (Var vapply `mkTyApps` [arg_ty, res_ty] `mkApps` [vclo, varg],
              Var lapply `mkTyApps` [arg_ty, res_ty] `mkApps` [lclo, larg])

373
buildClosures :: [TyVar] -> [VVar] -> [Type] -> Type -> VM VExpr -> VM VExpr
twanvl's avatar
twanvl committed
374
buildClosures _   _    [] _ mk_body
375
  = mk_body
376
377
378
buildClosures tvs vars [arg_ty] res_ty mk_body
  = buildClosure tvs vars arg_ty res_ty mk_body
buildClosures tvs vars (arg_ty : arg_tys) res_ty mk_body
379
380
381
  = do
      res_ty' <- mkClosureTypes arg_tys res_ty
      arg <- newLocalVVar FSLIT("x") arg_ty
382
      buildClosure tvs vars arg_ty res_ty'
383
        . hoistPolyVExpr tvs
384
        $ do
385
386
            lc <- builtin liftingContext
            clo <- buildClosures tvs (vars ++ [arg]) arg_tys res_ty mk_body
387
388
            return $ vLams lc (vars ++ [arg]) clo

389
390
391
392
-- (clo <x1,...,xn> <f,f^>, aclo (Arr lc xs1 ... xsn) <f,f^>)
--   where
--     f  = \env v -> case env of <x1,...,xn> -> e x1 ... xn v
--     f^ = \env v -> case env of Arr l xs1 ... xsn -> e^ l x1 ... xn v
393
--
394
395
buildClosure :: [TyVar] -> [VVar] -> Type -> Type -> VM VExpr -> VM VExpr
buildClosure tvs vars arg_ty res_ty mk_body
396
  = do
397
      (env_ty, env, bind) <- buildEnv vars
398
399
      env_bndr <- newLocalVVar FSLIT("env") env_ty
      arg_bndr <- newLocalVVar FSLIT("arg") arg_ty
400

401
      fn <- hoistPolyVExpr tvs
402
          $ do
403
              lc    <- builtin liftingContext
404
405
              body  <- mk_body
              body' <- bind (vVar env_bndr)
406
                            (vVarApps lc body (vars ++ [arg_bndr]))
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
407
              return (vLamsWithoutLC [env_bndr, arg_bndr] body')
408

409
      mkClosure arg_ty res_ty env_ty fn env
410

411
412
buildEnv :: [VVar] -> VM (Type, VExpr, VExpr -> VExpr -> VM VExpr)
buildEnv vvs
413
  = do
414
      lc <- builtin liftingContext
415
      let (ty, venv, vbind) = mkVectEnv tys vs
416
      (lenv, lbind) <- mkLiftEnv lc tys ls
417
      return (ty, (venv, lenv),
418
419
420
421
422
              \(venv,lenv) (vbody,lbody) ->
              do
                let vbody' = vbind venv vbody
                lbody' <- lbind lenv lbody
                return (vbody', lbody'))
423
  where
424
425
    (vs,ls) = unzip vvs
    tys     = map idType vs
426
427

mkVectEnv :: [Type] -> [Var] -> (Type, CoreExpr, CoreExpr -> CoreExpr -> CoreExpr)
twanvl's avatar
twanvl committed
428
mkVectEnv []   []  = (unitTy, Var unitDataConId, \_ body -> body)
429
430
431
432
433
434
435
mkVectEnv [ty] [v] = (ty, Var v, \env body -> Let (NonRec v env) body)
mkVectEnv tys  vs  = (ty, mkCoreTup (map Var vs),
                        \env body -> Case env (mkWildId ty) (exprType body)
                                       [(DataAlt (tupleCon Boxed (length vs)), vs, body)])
  where
    ty = mkCoreTupTy tys

436
mkLiftEnv :: Var -> [Type] -> [Var] -> VM (CoreExpr, CoreExpr -> CoreExpr -> VM CoreExpr)
437
mkLiftEnv lc [ty] [v]
438
439
  = return (Var v, \env body ->
                   do
440
                     len <- lengthPA ty (Var v)
441
                     return . Let (NonRec v env)
442
                            $ Case len lc (exprType body) [(DEFAULT, [], body)])
443
444

-- NOTE: this transparently deals with empty environments
445
mkLiftEnv lc tys vs
446
  = do
447
      (env_tc, env_tyargs) <- parrayReprTyCon vty
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
448
449
450
451
452

      bndrs <- if null vs then do
                                 v <- newDummyVar unitTy
                                 return [v]
                          else return vs
453
454
455
      let [env_con] = tyConDataCons env_tc
          
          env = Var (dataConWrapId env_con)
456
                `mkTyApps`  env_tyargs
457
                `mkApps`    (Var lc : args)
458

459
460
          bind env body = let scrut = unwrapFamInstScrut env_tc env_tyargs env
                          in
461
462
                          return $ Case scrut (mkWildId (exprType scrut))
                                        (exprType body)
463
                                        [(DataAlt env_con, lc : bndrs, body)]
464
465
466
467
      return (env, bind)
  where
    vty = mkCoreTupTy tys

468
469
470
    args  | null vs   = [Var unitDataConId]
          | otherwise = map Var vs