[project @ 2001-03-19 16:26:09 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreSyn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CoreSyn]{A data type for the Haskell compiler midsection}
5
6 \begin{code}
7 module CoreSyn (
8         Expr(..), Alt, Bind(..), AltCon(..), Arg, Note(..),
9         CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
10         TaggedExpr, TaggedAlt, TaggedBind, TaggedArg,
11
12         mkLets, mkLams, 
13         mkApps, mkTyApps, mkValApps, mkVarApps,
14         mkLit, mkIntLitInt, mkIntLit, 
15         mkConApp, 
16         varToCoreExpr,
17
18         isTyVar, isId, 
19         bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts, 
20         collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
21         collectArgs, collectBindersIgnoringNotes,
22         coreExprCc,
23         flattenBinds, 
24
25         isValArg, isTypeArg, valArgCount, valBndrCount,
26
27         -- Unfoldings
28         Unfolding(..),  UnfoldingGuidance(..),  -- Both abstract everywhere but in CoreUnfold.lhs
29         noUnfolding, mkOtherCon,
30         unfoldingTemplate, maybeUnfoldingTemplate, otherCons, 
31         isValueUnfolding, isEvaldUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
32         hasUnfolding, hasSomeUnfolding, neverUnfold,
33
34         -- Seq stuff
35         seqRules, seqExpr, seqExprs, seqUnfolding,
36
37         -- Annotated expressions
38         AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt, 
39         deAnnotate, deAnnotate', deAnnAlt,
40
41         -- Core rules
42         CoreRules(..),  -- Representation needed by friends
43         CoreRule(..),   -- CoreSubst, CoreTidy, CoreFVs, PprCore only
44         IdCoreRule,
45         RuleName,
46         emptyCoreRules, isEmptyCoreRules, rulesRhsFreeVars, rulesRules,
47         isBuiltinRule
48     ) where
49
50 #include "HsVersions.h"
51
52 import CostCentre       ( CostCentre, noCostCentre )
53 import Var              ( Var, Id, TyVar, isTyVar, isId )
54 import Type             ( Type, mkTyVarTy, seqType )
55 import Literal          ( Literal, mkMachInt )
56 import DataCon          ( DataCon, dataConId )
57 import VarSet
58 import Outputable
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection{The main data types}
64 %*                                                                      *
65 %************************************************************************
66
67 These data types are the heart of the compiler
68
69 \begin{code}
70 infixl 8 `App`  -- App brackets to the left
71
72 data Expr b     -- "b" for the type of binders, 
73   = Var   Id
74   | Lit   Literal
75   | App   (Expr b) (Arg b)
76   | Lam   b (Expr b)
77   | Let   (Bind b) (Expr b)
78   | Case  (Expr b) b [Alt b]    -- Binder gets bound to value of scrutinee
79                                 -- DEFAULT case must be last, if it occurs at all
80   | Note  Note (Expr b)
81   | Type  Type                  -- This should only show up at the top
82                                 -- level of an Arg
83
84 type Arg b = Expr b             -- Can be a Type
85
86 type Alt b = (AltCon, [b], Expr b)      -- (DEFAULT, [], rhs) is the default alternative
87
88 data AltCon = DataAlt DataCon
89             | LitAlt  Literal
90             | DEFAULT
91          deriving (Eq, Ord)
92
93 data Bind b = NonRec b (Expr b)
94               | Rec [(b, (Expr b))]
95
96 data Note
97   = SCC CostCentre
98
99   | Coerce      
100         Type            -- The to-type:   type of whole coerce expression
101         Type            -- The from-type: type of enclosed expression
102
103   | InlineCall          -- Instructs simplifier to inline
104                         -- the enclosed call
105
106   | InlineMe            -- Instructs simplifer to treat the enclosed expression
107                         -- as very small, and inline it at its call sites
108
109 -- NOTE: we also treat expressions wrapped in InlineMe as
110 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
111 -- What this means is that we obediently inline even things that don't
112 -- look like valuse.  This is sometimes important:
113 --      {-# INLINE f #-}
114 --      f = g . h
115 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
116 -- inside an INLINE, so it'll stay looking like a redex.  Nevertheless, we 
117 -- should inline f even inside lambdas.  In effect, we should trust the programmer.
118 \end{code}
119
120 INVARIANTS:
121
122 * The RHS of a letrec, and the RHSs of all top-level lets,
123   must be of LIFTED type.
124
125 * The RHS of a let, may be of UNLIFTED type, but only if the expression 
126   is ok-for-speculation.  This means that the let can be floated around 
127   without difficulty.  e.g.
128         y::Int# = x +# 1#       ok
129         y::Int# = fac 4#        not ok [use case instead]
130
131 * The argument of an App can be of any type.
132
133 * The simplifier tries to ensure that if the RHS of a let is a constructor
134   application, its arguments are trivial, so that the constructor can be
135   inlined vigorously.
136
137
138 %************************************************************************
139 %*                                                                      *
140 \subsection{Transformation rules}
141 %*                                                                      *
142 %************************************************************************
143
144 The CoreRule type and its friends are dealt with mainly in CoreRules,
145 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
146
147 \begin{code}
148 data CoreRules 
149   = Rules [CoreRule]
150           VarSet                -- Locally-defined free vars of RHSs
151
152 emptyCoreRules :: CoreRules
153 emptyCoreRules = Rules [] emptyVarSet
154
155 isEmptyCoreRules :: CoreRules -> Bool
156 isEmptyCoreRules (Rules rs _) = null rs
157
158 rulesRhsFreeVars :: CoreRules -> VarSet
159 rulesRhsFreeVars (Rules _ fvs) = fvs
160
161 rulesRules :: CoreRules -> [CoreRule]
162 rulesRules (Rules rules _) = rules
163 \end{code}
164
165 \begin{code}
166 type RuleName = FAST_STRING
167 type IdCoreRule = (Id,CoreRule)         -- Rules don't have their leading Id inside them
168
169 data CoreRule
170   = Rule RuleName
171          [CoreBndr]     -- Forall'd variables
172          [CoreExpr]     -- LHS args
173          CoreExpr       -- RHS
174
175   | BuiltinRule         -- Built-in rules are used for constant folding
176                         -- and suchlike.  It has no free variables.
177         ([CoreExpr] -> Maybe (RuleName, CoreExpr))
178
179 isBuiltinRule (BuiltinRule _) = True
180 isBuiltinRule _               = False
181 \end{code}
182
183
184 %************************************************************************
185 %*                                                                      *
186 \subsection{@Unfolding@ type}
187 %*                                                                      *
188 %************************************************************************
189
190 The @Unfolding@ type is declared here to avoid numerous loops, but it
191 should be abstract everywhere except in CoreUnfold.lhs
192
193 \begin{code}
194 data Unfolding
195   = NoUnfolding
196
197   | OtherCon [AltCon]           -- It ain't one of these
198                                 -- (OtherCon xs) also indicates that something has been evaluated
199                                 -- and hence there's no point in re-evaluating it.
200                                 -- OtherCon [] is used even for non-data-type values
201                                 -- to indicated evaluated-ness.  Notably:
202                                 --      data C = C !(Int -> Int)
203                                 --      case x of { C f -> ... }
204                                 -- Here, f gets an OtherCon [] unfolding.
205
206   | CompulsoryUnfolding CoreExpr        -- There is no "original" definition,
207                                         -- so you'd better unfold.
208
209   | CoreUnfolding                       -- An unfolding with redundant cached information
210                 CoreExpr                -- Template; binder-info is correct
211                 Bool                    -- True <=> top level binding
212                 Bool                    -- exprIsValue template (cached); it is ok to discard a `seq` on
213                                         --      this variable
214                 Bool                    -- True <=> doesn't waste (much) work to expand inside an inlining
215                                         --      Basically it's exprIsCheap
216                 UnfoldingGuidance       -- Tells about the *size* of the template.
217
218
219 data UnfoldingGuidance
220   = UnfoldNever
221   | UnfoldIfGoodArgs    Int     -- and "n" value args
222
223                         [Int]   -- Discount if the argument is evaluated.
224                                 -- (i.e., a simplification will definitely
225                                 -- be possible).  One elt of the list per *value* arg.
226
227                         Int     -- The "size" of the unfolding; to be elaborated
228                                 -- later. ToDo
229
230                         Int     -- Scrutinee discount: the discount to substract if the thing is in
231                                 -- a context (case (thing args) of ...),
232                                 -- (where there are the right number of arguments.)
233
234 noUnfolding = NoUnfolding
235 mkOtherCon  = OtherCon
236
237 seqUnfolding :: Unfolding -> ()
238 seqUnfolding (CoreUnfolding e top b1 b2 g)
239   = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
240 seqUnfolding other = ()
241
242 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
243 seqGuidance other                       = ()
244 \end{code}
245
246 \begin{code}
247 unfoldingTemplate :: Unfolding -> CoreExpr
248 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
249 unfoldingTemplate (CompulsoryUnfolding expr)   = expr
250 unfoldingTemplate other = panic "getUnfoldingTemplate"
251
252 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
253 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
254 maybeUnfoldingTemplate (CompulsoryUnfolding expr)   = Just expr
255 maybeUnfoldingTemplate other                        = Nothing
256
257 otherCons :: Unfolding -> [AltCon]
258 otherCons (OtherCon cons) = cons
259 otherCons other           = []
260
261 isValueUnfolding :: Unfolding -> Bool
262         -- Returns False for OtherCon
263 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
264 isValueUnfolding other                            = False
265
266 isEvaldUnfolding :: Unfolding -> Bool
267         -- Returns True for OtherCon
268 isEvaldUnfolding (OtherCon _)                     = True
269 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
270 isEvaldUnfolding other                            = False
271
272 isCheapUnfolding :: Unfolding -> Bool
273 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
274 isCheapUnfolding other                            = False
275
276 isCompulsoryUnfolding :: Unfolding -> Bool
277 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
278 isCompulsoryUnfolding other                   = False
279
280 hasUnfolding :: Unfolding -> Bool
281 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
282 hasUnfolding (CompulsoryUnfolding _)   = True
283 hasUnfolding other                     = False
284
285 hasSomeUnfolding :: Unfolding -> Bool
286 hasSomeUnfolding NoUnfolding = False
287 hasSomeUnfolding other       = True
288
289 neverUnfold :: Unfolding -> Bool
290 neverUnfold NoUnfolding                         = True
291 neverUnfold (OtherCon _)                        = True
292 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
293 neverUnfold other                               = False
294 \end{code}
295
296
297 %************************************************************************
298 %*                                                                      *
299 \subsection{The main data type}
300 %*                                                                      *
301 %************************************************************************
302
303 \begin{code}
304 -- The Ord is needed for the FiniteMap used in the lookForConstructor
305 -- in SimplEnv.  If you declared that lookForConstructor *ignores*
306 -- constructor-applications with LitArg args, then you could get
307 -- rid of this Ord.
308
309 instance Outputable AltCon where
310   ppr (DataAlt dc) = ppr dc
311   ppr (LitAlt lit) = ppr lit
312   ppr DEFAULT      = ptext SLIT("__DEFAULT")
313
314 instance Show AltCon where
315   showsPrec p con = showsPrecSDoc p (ppr con)
316 \end{code}
317
318
319 %************************************************************************
320 %*                                                                      *
321 \subsection{Useful synonyms}
322 %*                                                                      *
323 %************************************************************************
324
325 The common case
326
327 \begin{code}
328 type CoreBndr = Var
329 type CoreExpr = Expr CoreBndr
330 type CoreArg  = Arg  CoreBndr
331 type CoreBind = Bind CoreBndr
332 type CoreAlt  = Alt  CoreBndr
333 \end{code}
334
335 Binders are ``tagged'' with a \tr{t}:
336
337 \begin{code}
338 type Tagged t = (CoreBndr, t)
339
340 type TaggedBind t = Bind (Tagged t)
341 type TaggedExpr t = Expr (Tagged t)
342 type TaggedArg  t = Arg  (Tagged t)
343 type TaggedAlt  t = Alt  (Tagged t)
344 \end{code}
345
346
347 %************************************************************************
348 %*                                                                      *
349 \subsection{Core-constructing functions with checking}
350 %*                                                                      *
351 %************************************************************************
352
353 \begin{code}
354 mkApps    :: Expr b -> [Arg b]  -> Expr b
355 mkTyApps  :: Expr b -> [Type]   -> Expr b
356 mkValApps :: Expr b -> [Expr b] -> Expr b
357 mkVarApps :: Expr b -> [Var] -> Expr b
358
359 mkApps    f args = foldl App                       f args
360 mkTyApps  f args = foldl (\ e a -> App e (Type a)) f args
361 mkValApps f args = foldl (\ e a -> App e a)        f args
362 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
363
364 mkLit         :: Literal -> Expr b
365 mkIntLit      :: Integer -> Expr b
366 mkIntLitInt   :: Int     -> Expr b
367 mkConApp      :: DataCon -> [Arg b] -> Expr b
368 mkLets        :: [Bind b] -> Expr b -> Expr b
369 mkLams        :: [b] -> Expr b -> Expr b
370
371 mkLit lit         = Lit lit
372 mkConApp con args = mkApps (Var (dataConId con)) args
373
374 mkLams binders body = foldr Lam body binders
375 mkLets binds body   = foldr Let body binds
376
377 mkIntLit    n = Lit (mkMachInt n)
378 mkIntLitInt n = Lit (mkMachInt (toInteger n))
379
380 varToCoreExpr :: CoreBndr -> Expr b
381 varToCoreExpr v | isId v    = Var v
382                 | otherwise = Type (mkTyVarTy v)
383 \end{code}
384
385
386 %************************************************************************
387 %*                                                                      *
388 \subsection{Simple access functions}
389 %*                                                                      *
390 %************************************************************************
391
392 \begin{code}
393 bindersOf  :: Bind b -> [b]
394 bindersOf (NonRec binder _) = [binder]
395 bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
396
397 bindersOfBinds :: [Bind b] -> [b]
398 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
399
400 rhssOfBind :: Bind b -> [Expr b]
401 rhssOfBind (NonRec _ rhs) = [rhs]
402 rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
403
404 rhssOfAlts :: [Alt b] -> [Expr b]
405 rhssOfAlts alts = [e | (_,_,e) <- alts]
406
407 flattenBinds :: [Bind b] -> [(b, Expr b)]       -- Get all the lhs/rhs pairs
408 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
409 flattenBinds (Rec prs1   : binds) = prs1 ++ flattenBinds binds
410 flattenBinds []                   = []
411 \end{code}
412
413 We often want to strip off leading lambdas before getting down to
414 business.  @collectBinders@ is your friend.
415
416 We expect (by convention) type-, and value- lambdas in that
417 order.
418
419 \begin{code}
420 collectBinders               :: Expr b -> ([b],         Expr b)
421 collectBindersIgnoringNotes  :: Expr b -> ([b],         Expr b)
422 collectTyBinders             :: CoreExpr -> ([TyVar],     CoreExpr)
423 collectValBinders            :: CoreExpr -> ([Id],        CoreExpr)
424 collectTyAndValBinders       :: CoreExpr -> ([TyVar], [Id], CoreExpr)
425
426 collectBinders expr
427   = go [] expr
428   where
429     go bs (Lam b e) = go (b:bs) e
430     go bs e          = (reverse bs, e)
431
432 -- This one ignores notes.  It's used in CoreUnfold and StrAnal
433 -- when we aren't going to put the expression back together from
434 -- the pieces, so we don't mind losing the Notes
435 collectBindersIgnoringNotes expr
436   = go [] expr
437   where
438     go bs (Lam b e)  = go (b:bs) e
439     go bs (Note _ e) = go    bs  e
440     go bs e          = (reverse bs, e)
441
442 collectTyAndValBinders expr
443   = (tvs, ids, body)
444   where
445     (tvs, body1) = collectTyBinders expr
446     (ids, body)  = collectValBinders body1
447
448 collectTyBinders expr
449   = go [] expr
450   where
451     go tvs (Lam b e) | isTyVar b = go (b:tvs) e
452     go tvs e                     = (reverse tvs, e)
453
454 collectValBinders expr
455   = go [] expr
456   where
457     go ids (Lam b e) | isId b = go (b:ids) e
458     go ids body               = (reverse ids, body)
459 \end{code}
460
461
462 @collectArgs@ takes an application expression, returning the function
463 and the arguments to which it is applied.
464
465 \begin{code}
466 collectArgs :: Expr b -> (Expr b, [Arg b])
467 collectArgs expr
468   = go expr []
469   where
470     go (App f a) as = go f (a:as)
471     go e         as = (e, as)
472 \end{code}
473
474 coreExprCc gets the cost centre enclosing an expression, if any.
475 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
476
477 \begin{code}
478 coreExprCc :: Expr b -> CostCentre
479 coreExprCc (Note (SCC cc) e)   = cc
480 coreExprCc (Note other_note e) = coreExprCc e
481 coreExprCc (Lam _ e)           = coreExprCc e
482 coreExprCc other               = noCostCentre
483 \end{code}
484
485
486
487 %************************************************************************
488 %*                                                                      *
489 \subsection{Predicates}
490 %*                                                                      *
491 %************************************************************************
492
493 \begin{code}
494 isValArg (Type _) = False
495 isValArg other    = True
496
497 isTypeArg (Type _) = True
498 isTypeArg other    = False
499
500 valBndrCount :: [CoreBndr] -> Int
501 valBndrCount []                   = 0
502 valBndrCount (b : bs) | isId b    = 1 + valBndrCount bs
503                       | otherwise = valBndrCount bs
504
505 valArgCount :: [Arg b] -> Int
506 valArgCount []              = 0
507 valArgCount (Type _ : args) = valArgCount args
508 valArgCount (other  : args) = 1 + valArgCount args
509 \end{code}
510
511
512 %************************************************************************
513 %*                                                                      *
514 \subsection{Seq stuff}
515 %*                                                                      *
516 %************************************************************************
517
518 \begin{code}
519 seqExpr :: CoreExpr -> ()
520 seqExpr (Var v)       = v `seq` ()
521 seqExpr (Lit lit)     = lit `seq` ()
522 seqExpr (App f a)     = seqExpr f `seq` seqExpr a
523 seqExpr (Lam b e)     = seqBndr b `seq` seqExpr e
524 seqExpr (Let b e)     = seqBind b `seq` seqExpr e
525 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
526 seqExpr (Note n e)    = seqNote n `seq` seqExpr e
527 seqExpr (Type t)      = seqType t
528
529 seqExprs [] = ()
530 seqExprs (e:es) = seqExpr e `seq` seqExprs es
531
532 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
533 seqNote other          = ()
534
535 seqBndr b = b `seq` ()
536
537 seqBndrs [] = ()
538 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
539
540 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
541 seqBind (Rec prs)    = seqPairs prs
542
543 seqPairs [] = ()
544 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
545
546 seqAlts [] = ()
547 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
548
549 seqRules :: CoreRules -> ()
550 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
551
552 seq_rules [] = ()
553 seq_rules (Rule fs bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
554 seq_rules (BuiltinRule _ : rules) = seq_rules rules
555 \end{code}
556
557
558
559 %************************************************************************
560 %*                                                                      *
561 \subsection{Annotated core; annotation at every node in the tree}
562 %*                                                                      *
563 %************************************************************************
564
565 \begin{code}
566 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
567
568 data AnnExpr' bndr annot
569   = AnnVar      Id
570   | AnnLit      Literal
571   | AnnLam      bndr (AnnExpr bndr annot)
572   | AnnApp      (AnnExpr bndr annot) (AnnExpr bndr annot)
573   | AnnCase     (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
574   | AnnLet      (AnnBind bndr annot) (AnnExpr bndr annot)
575   | AnnNote     Note (AnnExpr bndr annot)
576   | AnnType     Type
577
578 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
579
580 data AnnBind bndr annot
581   = AnnNonRec bndr (AnnExpr bndr annot)
582   | AnnRec    [(bndr, AnnExpr bndr annot)]
583 \end{code}
584
585 \begin{code}
586 deAnnotate :: AnnExpr bndr annot -> Expr bndr
587 deAnnotate (_, e) = deAnnotate' e
588
589 deAnnotate' (AnnType t)           = Type t
590 deAnnotate' (AnnVar  v)           = Var v
591 deAnnotate' (AnnLit  lit)         = Lit lit
592 deAnnotate' (AnnLam  binder body) = Lam binder (deAnnotate body)
593 deAnnotate' (AnnApp  fun arg)     = App (deAnnotate fun) (deAnnotate arg)
594 deAnnotate' (AnnNote note body)   = Note note (deAnnotate body)
595
596 deAnnotate' (AnnLet bind body)
597   = Let (deAnnBind bind) (deAnnotate body)
598   where
599     deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
600     deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
601
602 deAnnotate' (AnnCase scrut v alts)
603   = Case (deAnnotate scrut) v (map deAnnAlt alts)
604
605 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
606 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
607 \end{code}
608