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