[project @ 1996-06-05 06:44:31 by partain]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreSyn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[CoreSyn]{A data type for the Haskell compiler midsection}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module CoreSyn (
10         GenCoreBinding(..), GenCoreExpr(..),
11         GenCoreArg(..), GenCoreBinder(..), GenCoreCaseAlts(..),
12         GenCoreCaseDefault(..),
13         Coercion(..),
14
15         bindersOf, pairsFromCoreBinds, rhssOfBind,
16
17         mkGenApp, mkValApp, mkTyApp, mkUseApp,
18         mkApp, mkCon, mkPrim,
19         mkValLam, mkTyLam, mkUseLam,
20         mkLam,
21         collectBinders, isValBinder, notValBinder,
22         
23         collectArgs, isValArg, notValArg, numValArgs,
24
25         mkCoLetAny, mkCoLetNoUnboxed, mkCoLetUnboxedToCase,
26         mkCoLetsAny, mkCoLetsNoUnboxed, mkCoLetsUnboxedToCase,
27         mkCoLetrecAny, mkCoLetrecNoUnboxed,
28
29         rhssOfAlts,
30
31         -- Common type instantiation...
32         CoreBinding(..),
33         CoreExpr(..),
34         CoreBinder(..),
35         CoreArg(..),
36         CoreCaseAlts(..),
37         CoreCaseDefault(..),
38
39         -- And not-so-common type instantiations...
40         TaggedCoreBinding(..),
41         TaggedCoreExpr(..),
42         TaggedCoreBinder(..),
43         TaggedCoreArg(..),
44         TaggedCoreCaseAlts(..),
45         TaggedCoreCaseDefault(..),
46
47         SimplifiableCoreBinding(..),
48         SimplifiableCoreExpr(..),
49         SimplifiableCoreBinder(..),
50         SimplifiableCoreArg(..),
51         SimplifiableCoreCaseAlts(..),
52         SimplifiableCoreCaseDefault(..)
53     ) where
54
55 IMP_Ubiq(){-uitous-}
56
57 -- ToDo:rm:
58 --import PprCore                ( GenCoreExpr{-instance-} )
59 --import PprStyle               ( PprStyle(..) )
60
61 import CostCentre       ( showCostCentre, CostCentre )
62 import Id               ( idType, GenId{-instance Eq-} )
63 import Type             ( isUnboxedType )
64 import Usage            ( UVar(..) )
65 import Util             ( panic, assertPanic {-pprTrace:ToDo:rm-} )
66 \end{code}
67
68 %************************************************************************
69 %*                                                                      *
70 \subsection[CoreTopBinding_and_CoreBinding]{@CoreTopBinding@ and @GenCoreBinding@}
71 %*                                                                      *
72 %************************************************************************
73
74 Core programs, bindings, expressions, etc., are parameterised with
75 respect to the information kept about binding and bound occurrences of
76 variables, called {\em binders} and {\em val_occ tyvar uvars}, respectively.  [I
77 don't really like the pair of names; I prefer {\em binder} and {\em
78 bounder}.  Or {\em binder} and {\em var}.]
79
80 A @GenCoreBinding@ is either a single non-recursive binding of a
81 ``binder'' to an expression, or a mutually-recursive blob of same.
82 \begin{code}
83 data GenCoreBinding val_bdr val_occ tyvar uvar
84   = NonRec      val_bdr (GenCoreExpr val_bdr val_occ tyvar uvar)
85   | Rec         [(val_bdr, GenCoreExpr val_bdr val_occ tyvar uvar)]
86 \end{code}
87
88 \begin{code}
89 bindersOf :: GenCoreBinding val_bdr val_occ tyvar uvar -> [val_bdr]
90
91 pairsFromCoreBinds ::
92   [GenCoreBinding val_bdr val_occ tyvar uvar] ->
93   [(val_bdr, GenCoreExpr val_bdr val_occ tyvar uvar)]
94
95 rhssOfBind :: GenCoreBinding val_bdr val_occ tyvar uvar -> [GenCoreExpr val_bdr val_occ tyvar uvar]
96
97 bindersOf (NonRec binder _) = [binder]
98 bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
99
100 pairsFromCoreBinds []                  = []
101 pairsFromCoreBinds ((NonRec b e) : bs) = (b,e) :  pairsFromCoreBinds bs
102 pairsFromCoreBinds ((Rec  pairs) : bs) = pairs ++ pairsFromCoreBinds bs
103
104 rhssOfBind (NonRec _ rhs) = [rhs]
105 rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
106 \end{code}
107
108 %************************************************************************
109 %*                                                                      *
110 \subsection[GenCoreExpr]{Core expressions: @GenCoreExpr@}
111 %*                                                                      *
112 %************************************************************************
113
114 @GenCoreExpr@ is the heart of the ``core'' data types; it is
115 (more-or-less) boiled-down second-order polymorphic lambda calculus.
116 For types in the core world, we just keep using @Types@.
117 \begin{code}
118 data GenCoreExpr val_bdr val_occ tyvar uvar
119      = Var    val_occ
120      | Lit    Literal   -- literal constants
121 \end{code}
122
123 @Cons@ and @Prims@ are saturated constructor and primitive-op
124 applications (see the comment).  Note: @Con@s are only set up by the
125 simplifier (and by the desugarer when it knows what it's doing).  The
126 desugarer sets up constructors as applications of global @Vars@s.
127
128 \begin{code}
129      | Con      Id [GenCoreArg val_occ tyvar uvar]
130                 -- Saturated constructor application:
131                 -- The constructor is a function of the form:
132                 --      /\ a1 -> ... /\ am -> \ b1 -> ... \ bn ->
133                 -- <expr> where "/\" is a type lambda and "\" the
134                 -- regular kind; there will be "m" Types and
135                 -- "n" bindees in the Con args.
136
137      | Prim     PrimOp [GenCoreArg val_occ tyvar uvar]
138                 -- saturated primitive operation;
139                 -- comment on Cons applies here, too.
140 \end{code}
141
142 Ye olde abstraction and application operators.
143 \begin{code}
144      | Lam      (GenCoreBinder val_bdr tyvar uvar)
145                 (GenCoreExpr   val_bdr val_occ tyvar uvar)
146
147      | App      (GenCoreExpr val_bdr val_occ tyvar uvar)
148                 (GenCoreArg  val_occ tyvar uvar)
149 \end{code}
150
151 Case expressions (\tr{case <expr> of <List of alternatives>}): there
152 are really two flavours masquerading here---those for scrutinising
153 {\em algebraic} types and those for {\em primitive} types.  Please see
154 under @GenCoreCaseAlts@.
155 \begin{code}
156      | Case     (GenCoreExpr val_bdr val_occ tyvar uvar)
157                 (GenCoreCaseAlts val_bdr val_occ tyvar uvar)
158 \end{code}
159
160 A Core case expression \tr{case e of v -> ...} implies evaluation of
161 \tr{e}; it is not equivalent to \tr{let v = in ...} (as with a Haskell
162 \tr{case}).
163
164 Non-recursive @Lets@ only have one binding; having more than one
165 doesn't buy you much, and it is an easy way to mess up variable
166 scoping.
167 \begin{code}
168      | Let      (GenCoreBinding val_bdr val_occ tyvar uvar)
169                 (GenCoreExpr val_bdr val_occ tyvar uvar)
170                 -- both recursive and non-.
171                 -- The "GenCoreBinding" records that information
172 \end{code}
173
174 For cost centre scc expressions we introduce a new core construct
175 @SCC@ so transforming passes have to deal with it explicitly. The
176 alternative of using a new PrimativeOp may result in a bad
177 transformations of which we are unaware.
178 \begin{code}
179      | SCC      CostCentre                                  -- label of scc
180                 (GenCoreExpr val_bdr val_occ tyvar uvar)    -- scc expression
181 \end{code}
182
183 Coercions arise from uses of the constructor of a @newtype@
184 declaration, either in construction (resulting in a @CoreceIn@) or
185 pattern matching (resulting in a @CoerceOut@).
186
187 \begin{code}
188     | Coerce    Coercion
189                 (GenType tyvar uvar)            -- Type of the whole expression
190                 (GenCoreExpr val_bdr val_occ tyvar uvar)
191 \end{code}
192
193 \begin{code}
194 data Coercion   = CoerceIn Id           -- Apply this constructor
195                 | CoerceOut Id          -- Strip this constructor
196 \end{code}
197
198
199 %************************************************************************
200 %*                                                                      *
201 \subsection{Core-constructing functions with checking}
202 %*                                                                      *
203 %************************************************************************
204
205 When making @Lets@, we may want to take evasive action if the thing
206 being bound has unboxed type. We have different variants ...
207
208 @mkCoLet(s|rec)Any@             let-binds any binding, regardless of type
209 @mkCoLet(s|rec)NoUnboxed@       prohibits unboxed bindings
210 @mkCoLet(s)UnboxedToCase@       converts an unboxed binding to a case
211                                 (unboxed bindings in a letrec are still prohibited)
212
213 \begin{code}
214 mkCoLetAny :: GenCoreBinding Id Id tyvar uvar
215            -> GenCoreExpr    Id Id tyvar uvar
216            -> GenCoreExpr    Id Id tyvar uvar
217 mkCoLetsAny :: [GenCoreBinding Id Id tyvar uvar] ->
218                 GenCoreExpr Id Id tyvar uvar ->
219                 GenCoreExpr Id Id tyvar uvar
220
221 mkCoLetrecAny :: [(val_bdr, GenCoreExpr val_bdr val_occ tyvar uvar)]
222               -> GenCoreExpr val_bdr val_occ tyvar uvar
223               -> GenCoreExpr val_bdr val_occ tyvar uvar
224
225 mkCoLetrecAny []    body = body
226 mkCoLetrecAny binds body = Let (Rec binds) body
227
228 mkCoLetsAny []    expr = expr
229 mkCoLetsAny binds expr = foldr mkCoLetAny expr binds
230
231 mkCoLetAny bind@(Rec binds) body = mkCoLetrecAny binds body
232 mkCoLetAny bind@(NonRec binder rhs) body
233   = case body of
234       Var binder2 | binder == binder2
235          -> rhs   -- hey, I have the rhs
236       other
237          -> Let bind body
238 \end{code}
239
240 \begin{code}
241 --mkCoLetNoUnboxed ::
242 --  GenCoreBinding val_bdr val_occ tyvar uvar ->
243 --  GenCoreExpr val_bdr val_occ tyvar uvar ->
244 --  GenCoreExpr val_bdr val_occ tyvar uvar
245
246 mkCoLetNoUnboxed bind@(Rec binds) body
247   = mkCoLetrecNoUnboxed binds body
248 mkCoLetNoUnboxed bind@(NonRec binder rhs) body
249   = --ASSERT (not (isUnboxedType (idType binder)))
250     case body of
251       Var binder2 | binder == binder2
252          -> rhs   -- hey, I have the rhs
253       other
254          -> Let bind body
255
256 mkCoLetsNoUnboxed []    expr = expr
257 mkCoLetsNoUnboxed binds expr = foldr mkCoLetNoUnboxed expr binds
258
259 mkCoLetrecNoUnboxed :: [(GenId (GenType a b), GenCoreExpr (GenId (GenType a b)) c d e)]
260                     -> GenCoreExpr (GenId (GenType a b)) c d e
261                     -> GenCoreExpr (GenId (GenType a b)) c d e
262
263 mkCoLetrecNoUnboxed []    body = body
264 mkCoLetrecNoUnboxed binds body
265   = ASSERT (all is_boxed_bind binds)
266     Let (Rec binds) body
267   where
268     is_boxed_bind (binder, rhs)
269       = (not . isUnboxedType . idType) binder
270 \end{code}
271
272 \begin{code}
273 --mkCoLetUnboxedToCase ::
274 --  GenCoreBinding val_bdr val_occ tyvar uvar ->
275 --  GenCoreExpr val_bdr val_occ tyvar uvar ->
276 --  GenCoreExpr val_bdr val_occ tyvar uvar
277
278 mkCoLetUnboxedToCase bind@(Rec binds) body
279   = mkCoLetrecNoUnboxed binds body
280 mkCoLetUnboxedToCase bind@(NonRec binder rhs) body
281   = case body of
282       Var binder2 | binder == binder2
283          -> rhs   -- hey, I have the rhs
284       other
285          -> if (not (isUnboxedType (idType binder))) then
286                 Let bind body            -- boxed...
287             else
288                 Case rhs                  -- unboxed...
289                   (PrimAlts []
290                     (BindDefault binder body))
291
292 mkCoLetsUnboxedToCase []    expr = expr
293 mkCoLetsUnboxedToCase binds expr = foldr mkCoLetUnboxedToCase expr binds
294 \end{code}
295
296 %************************************************************************
297 %*                                                                      *
298 \subsection{Case alternatives in @GenCoreExpr@}
299 %*                                                                      *
300 %************************************************************************
301
302 We have different kinds of @case@s, the differences being reflected in
303 the kinds of alternatives a case has.  We maintain a distinction
304 between cases for scrutinising algebraic datatypes, as opposed to
305 primitive types.  In both cases, we carry around a @TyCon@, as a
306 handle with which we can get info about the case (e.g., total number
307 of data constructors for this type).
308
309 For example:
310 \begin{verbatim}
311 let# x=e in b
312 \end{verbatim}
313 becomes
314 \begin{verbatim}
315 Case e [ BindDefaultAlt x -> b ]
316 \end{verbatim}
317
318 \begin{code}
319 data GenCoreCaseAlts val_bdr val_occ tyvar uvar
320   = AlgAlts     [(Id,                           -- alts: data constructor,
321                   [val_bdr],                    -- constructor's parameters,
322                   GenCoreExpr val_bdr val_occ tyvar uvar)]      -- rhs.
323                 (GenCoreCaseDefault val_bdr val_occ tyvar uvar)
324
325   | PrimAlts    [(Literal,                      -- alts: unboxed literal,
326                   GenCoreExpr val_bdr val_occ tyvar uvar)]      -- rhs.
327                 (GenCoreCaseDefault val_bdr val_occ tyvar uvar)
328
329 -- obvious things: if there are no alts in the list, then the default
330 -- can't be NoDefault.
331
332 data GenCoreCaseDefault val_bdr val_occ tyvar uvar
333   = NoDefault                                   -- small con family: all
334                                                 -- constructor accounted for
335   | BindDefault val_bdr                         -- form: var -> expr;
336                 (GenCoreExpr val_bdr val_occ tyvar uvar)        -- "val_bdr" may or may not
337                                                 -- be used in RHS.
338 \end{code}
339
340 \begin{code}
341 rhssOfAlts (AlgAlts alts deflt)  = rhssOfDeflt deflt ++ [rhs | (_,_,rhs) <- alts]
342 rhssOfAlts (PrimAlts alts deflt) = rhssOfDeflt deflt ++ [rhs | (_,rhs)   <- alts]
343
344 rhssOfDeflt NoDefault           = []
345 rhssOfDeflt (BindDefault _ rhs) = [rhs]
346 \end{code}
347
348 %************************************************************************
349 %*                                                                      *
350 \subsection{Core binders}
351 %*                                                                      *
352 %************************************************************************
353
354 \begin{code}
355 data GenCoreBinder val_bdr tyvar uvar
356   = ValBinder   val_bdr
357   | TyBinder    tyvar
358   | UsageBinder uvar
359
360 isValBinder (ValBinder _) = True
361 isValBinder _             = False
362
363 notValBinder = not . isValBinder
364 \end{code}
365
366 Clump Lams together if possible.
367
368 \begin{code}
369 mkValLam :: [val_bdr]
370          -> GenCoreExpr val_bdr val_occ tyvar uvar
371          -> GenCoreExpr val_bdr val_occ tyvar uvar
372 mkTyLam  :: [tyvar]
373          -> GenCoreExpr val_bdr val_occ tyvar uvar
374          -> GenCoreExpr val_bdr val_occ tyvar uvar
375 mkUseLam :: [uvar]
376          -> GenCoreExpr val_bdr val_occ tyvar uvar
377          -> GenCoreExpr val_bdr val_occ tyvar uvar
378
379 mkValLam binders body = foldr (Lam . ValBinder)   body binders
380 mkTyLam  binders body = foldr (Lam . TyBinder)    body binders
381 mkUseLam binders body = foldr (Lam . UsageBinder) body binders
382
383 mkLam :: [tyvar] -> [val_bdr] -- ToDo: could add a [uvar] arg...
384          -> GenCoreExpr val_bdr val_occ tyvar uvar
385          -> GenCoreExpr val_bdr val_occ tyvar uvar
386
387 mkLam tyvars valvars body
388   = mkTyLam tyvars (mkValLam valvars body)
389 \end{code}
390
391 We often want to strip off leading lambdas before getting down to
392 business.  @collectBinders@ is your friend.
393
394 We expect (by convention) usage-, type-, and value- lambdas in that
395 order.
396
397 \begin{code}
398 collectBinders ::
399   GenCoreExpr val_bdr val_occ tyvar uvar ->
400   ([uvar], [tyvar], [val_bdr], GenCoreExpr val_bdr val_occ tyvar uvar)
401
402 collectBinders expr
403   = usages expr []
404   where
405     usages (Lam (UsageBinder u) body) uacc = usages body (u:uacc)
406     usages other uacc
407       = case (tyvars other []) of { (tacc, vacc, expr) ->
408         (reverse uacc, tacc, vacc, expr) }
409
410     tyvars (Lam (TyBinder t)    body) tacc = tyvars body (t:tacc)
411     tyvars other tacc
412       = ASSERT(not (usage_lambda other))
413         case (valvars other []) of { (vacc, expr) ->
414         (reverse tacc, vacc, expr) }
415
416     valvars (Lam (ValBinder v)  body) vacc = valvars body (v:vacc)
417     valvars other vacc
418       = ASSERT(not (usage_lambda other))
419         ASSERT(not (tyvar_lambda other))
420         (reverse vacc, other)
421
422     ---------------------------------------
423     usage_lambda (Lam (UsageBinder _) _) = True
424     usage_lambda _                       = False
425
426     tyvar_lambda (Lam (TyBinder _) _)    = True
427     tyvar_lambda _                       = False
428 \end{code}
429
430 %************************************************************************
431 %*                                                                      *
432 \subsection{Core arguments (atoms)}
433 %*                                                                      *
434 %************************************************************************
435
436 \begin{code}
437 data GenCoreArg val_occ tyvar uvar
438   = LitArg      Literal
439   | VarArg      val_occ
440   | TyArg       (GenType tyvar uvar)
441   | UsageArg    (GenUsage uvar)
442 \end{code}
443
444 General and specific forms:
445 \begin{code}
446 mkGenApp :: GenCoreExpr val_bdr val_occ tyvar uvar
447          -> [GenCoreArg val_occ tyvar uvar]
448          -> GenCoreExpr val_bdr val_occ tyvar uvar
449 mkTyApp  :: GenCoreExpr val_bdr val_occ tyvar uvar
450          -> [GenType tyvar uvar]
451          -> GenCoreExpr val_bdr val_occ tyvar uvar
452 mkUseApp :: GenCoreExpr val_bdr val_occ tyvar uvar
453          -> [GenUsage uvar]
454          -> GenCoreExpr val_bdr val_occ tyvar uvar
455 mkValApp :: GenCoreExpr val_bdr val_occ tyvar uvar
456          -> [GenCoreArg val_occ tyvar uvar] -- but we ASSERT they are LitArg or VarArg
457          -> GenCoreExpr val_bdr val_occ tyvar uvar
458
459 mkGenApp f args = foldl App                                f args
460 mkTyApp  f args = foldl (\ e a -> App e (TyArg a))         f args
461 mkUseApp f args = foldl (\ e a -> App e (UsageArg a))      f args
462 mkValApp f args = foldl (\ e a -> App e (is_Lit_or_Var a)) f args
463
464 #ifndef DEBUG
465 is_Lit_or_Var a = a
466 #else
467 is_Lit_or_Var a
468   = if isValArg a then a else panic "CoreSyn.mkValApps:not LitArg or VarArg"
469 #endif
470
471 isValArg (LitArg _) = True  -- often used for sanity-checking
472 isValArg (VarArg _) = True
473 isValArg _          = False
474
475 notValArg = not . isValArg -- exists only because it's a common use of isValArg
476
477 numValArgs as = length [ a | a <- as, isValArg a ] -- again, convenience
478 \end{code}
479
480 \begin{code}
481 mkApp  fun = mk_thing (mkGenApp fun)
482 mkCon  con = mk_thing (Con      con)
483 mkPrim op  = mk_thing (Prim     op)
484
485 mk_thing thing uses tys vals
486   = thing (map UsageArg uses ++ map TyArg tys ++ map is_Lit_or_Var vals)
487 \end{code}
488
489 @collectArgs@ takes an application expression, returning the function
490 and the arguments to which it is applied.
491
492 \begin{code}
493 collectArgs :: GenCoreExpr val_bdr val_occ tyvar uvar
494             -> (GenCoreExpr val_bdr val_occ tyvar uvar,
495                 [GenUsage uvar],
496                 [GenType tyvar uvar],
497                 [GenCoreArg val_occ tyvar uvar]{-ValArgs-})
498
499 collectArgs expr
500   = valvars expr []
501   where
502     valvars (App fun v) vacc | isValArg v = valvars fun (v:vacc)
503     valvars fun vacc
504       = case (tyvars fun []) of { (expr, uacc, tacc) ->
505         (expr, uacc, tacc, vacc) }
506
507     tyvars (App fun (TyArg t))    tacc = tyvars fun (t:tacc)
508     tyvars fun tacc
509       = case (usages fun []) of { (expr, uacc) ->
510         (expr, uacc, tacc) }
511
512     usages (App fun (UsageArg u)) uacc = usages fun (u:uacc)
513     usages fun uacc
514       = (fun,uacc)
515 \end{code}
516
517 %************************************************************************
518 %*                                                                      *
519 \subsection{The main @Core*@ instantiation of the @GenCore*@ types}
520 %*                                                                      *
521 %************************************************************************
522
523 \begin{code}
524 type CoreBinding = GenCoreBinding  Id Id TyVar UVar
525 type CoreExpr    = GenCoreExpr     Id Id TyVar UVar
526 type CoreBinder  = GenCoreBinder   Id    TyVar UVar
527 type CoreArg     = GenCoreArg         Id TyVar UVar
528
529 type CoreCaseAlts    = GenCoreCaseAlts    Id Id TyVar UVar
530 type CoreCaseDefault = GenCoreCaseDefault Id Id TyVar UVar
531 \end{code}
532
533 %************************************************************************
534 %*                                                                      *
535 \subsection{The @TaggedCore*@ instantiation of the @GenCore*@ types}
536 %*                                                                      *
537 %************************************************************************
538
539 Binders are ``tagged'' with a \tr{t}:
540 \begin{code}
541 type Tagged t = (Id, t)
542
543 type TaggedCoreBinding t = GenCoreBinding (Tagged t) Id TyVar UVar
544 type TaggedCoreExpr    t = GenCoreExpr    (Tagged t) Id TyVar UVar
545 type TaggedCoreBinder  t = GenCoreBinder  (Tagged t)    TyVar UVar
546 type TaggedCoreArg     t = GenCoreArg                Id TyVar UVar
547
548 type TaggedCoreCaseAlts    t = GenCoreCaseAlts    (Tagged t) Id TyVar UVar
549 type TaggedCoreCaseDefault t = GenCoreCaseDefault (Tagged t) Id TyVar UVar
550 \end{code}
551
552 %************************************************************************
553 %*                                                                      *
554 \subsection{The @SimplifiableCore*@ instantiation of the @GenCore*@ types}
555 %*                                                                      *
556 %************************************************************************
557
558 Binders are tagged with @BinderInfo@:
559 \begin{code}
560 type Simplifiable = (Id, BinderInfo)
561
562 type SimplifiableCoreBinding = GenCoreBinding Simplifiable Id TyVar UVar
563 type SimplifiableCoreExpr    = GenCoreExpr    Simplifiable Id TyVar UVar
564 type SimplifiableCoreBinder  = GenCoreBinder  Simplifiable    TyVar UVar
565 type SimplifiableCoreArg     = GenCoreArg                  Id TyVar UVar
566
567 type SimplifiableCoreCaseAlts    = GenCoreCaseAlts    Simplifiable Id TyVar UVar
568 type SimplifiableCoreCaseDefault = GenCoreCaseDefault Simplifiable Id TyVar UVar
569 \end{code}