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