[project @ 2000-09-14 13:46:39 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         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                    -- True <=> top level binding
184                 Bool                    -- exprIsValue template (cached); it is ok to discard a `seq` on
185                                         --      this variable
186                 Bool                    -- True <=> doesn't waste (much) work to expand inside an inlining
187                                         --      Basically it's exprIsCheap
188                 UnfoldingGuidance       -- Tells about the *size* of the template.
189
190
191 data UnfoldingGuidance
192   = UnfoldNever
193   | UnfoldIfGoodArgs    Int     -- and "n" value args
194
195                         [Int]   -- Discount if the argument is evaluated.
196                                 -- (i.e., a simplification will definitely
197                                 -- be possible).  One elt of the list per *value* arg.
198
199                         Int     -- The "size" of the unfolding; to be elaborated
200                                 -- later. ToDo
201
202                         Int     -- Scrutinee discount: the discount to substract if the thing is in
203                                 -- a context (case (thing args) of ...),
204                                 -- (where there are the right number of arguments.)
205
206 noUnfolding = NoUnfolding
207 mkOtherCon  = OtherCon
208
209 seqUnfolding :: Unfolding -> ()
210 seqUnfolding (CoreUnfolding e top b1 b2 g)
211   = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
212 seqUnfolding other = ()
213
214 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
215 seqGuidance other                       = ()
216 \end{code}
217
218 \begin{code}
219 unfoldingTemplate :: Unfolding -> CoreExpr
220 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
221 unfoldingTemplate (CompulsoryUnfolding expr)   = expr
222 unfoldingTemplate other = panic "getUnfoldingTemplate"
223
224 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
225 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
226 maybeUnfoldingTemplate (CompulsoryUnfolding expr)   = Just expr
227 maybeUnfoldingTemplate other                        = Nothing
228
229 otherCons :: Unfolding -> [AltCon]
230 otherCons (OtherCon cons) = cons
231 otherCons other           = []
232
233 isValueUnfolding :: Unfolding -> Bool
234         -- Returns False for OtherCon
235 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
236 isValueUnfolding other                            = False
237
238 isEvaldUnfolding :: Unfolding -> Bool
239         -- Returns True for OtherCon
240 isEvaldUnfolding (OtherCon _)                     = True
241 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
242 isEvaldUnfolding other                            = False
243
244 isCheapUnfolding :: Unfolding -> Bool
245 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
246 isCheapUnfolding other                            = False
247
248 isCompulsoryUnfolding :: Unfolding -> Bool
249 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
250 isCompulsoryUnfolding other                   = False
251
252 hasUnfolding :: Unfolding -> Bool
253 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
254 hasUnfolding (CompulsoryUnfolding _)   = True
255 hasUnfolding other                     = False
256
257 hasSomeUnfolding :: Unfolding -> Bool
258 hasSomeUnfolding NoUnfolding = False
259 hasSomeUnfolding other       = True
260 \end{code}
261
262
263 %************************************************************************
264 %*                                                                      *
265 \subsection{The main data type}
266 %*                                                                      *
267 %************************************************************************
268
269 \begin{code}
270 -- The Ord is needed for the FiniteMap used in the lookForConstructor
271 -- in SimplEnv.  If you declared that lookForConstructor *ignores*
272 -- constructor-applications with LitArg args, then you could get
273 -- rid of this Ord.
274
275 instance Outputable AltCon where
276   ppr (DataAlt dc) = ppr dc
277   ppr (LitAlt lit) = ppr lit
278   ppr DEFAULT      = ptext SLIT("__DEFAULT")
279
280 instance Show AltCon where
281   showsPrec p con = showsPrecSDoc p (ppr con)
282 \end{code}
283
284
285 %************************************************************************
286 %*                                                                      *
287 \subsection{Useful synonyms}
288 %*                                                                      *
289 %************************************************************************
290
291 The common case
292
293 \begin{code}
294 type CoreBndr = Var
295 type CoreExpr = Expr CoreBndr
296 type CoreArg  = Arg  CoreBndr
297 type CoreBind = Bind CoreBndr
298 type CoreAlt  = Alt  CoreBndr
299 type CoreNote = Note
300 \end{code}
301
302 Binders are ``tagged'' with a \tr{t}:
303
304 \begin{code}
305 type Tagged t = (CoreBndr, t)
306
307 type TaggedBind t = Bind (Tagged t)
308 type TaggedExpr t = Expr (Tagged t)
309 type TaggedArg  t = Arg  (Tagged t)
310 type TaggedAlt  t = Alt  (Tagged t)
311 \end{code}
312
313
314 %************************************************************************
315 %*                                                                      *
316 \subsection{Core-constructing functions with checking}
317 %*                                                                      *
318 %************************************************************************
319
320 \begin{code}
321 mkApps    :: Expr b -> [Arg b]  -> Expr b
322 mkTyApps  :: Expr b -> [Type]   -> Expr b
323 mkValApps :: Expr b -> [Expr b] -> Expr b
324 mkVarApps :: Expr b -> [Var] -> Expr b
325
326 mkApps    f args = foldl App                       f args
327 mkTyApps  f args = foldl (\ e a -> App e (Type a)) f args
328 mkValApps f args = foldl (\ e a -> App e a)        f args
329 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
330
331 mkLit         :: Literal -> Expr b
332 mkIntLit      :: Integer -> Expr b
333 mkIntLitInt   :: Int     -> Expr b
334 mkConApp      :: DataCon -> [Arg b] -> Expr b
335 mkLets        :: [Bind b] -> Expr b -> Expr b
336 mkLams        :: [b] -> Expr b -> Expr b
337
338 mkLit lit         = Lit lit
339 mkConApp con args = mkApps (Var (dataConId con)) args
340
341 mkLams binders body = foldr Lam body binders
342 mkLets binds body   = foldr Let body binds
343
344 mkIntLit    n = Lit (mkMachInt n)
345 mkIntLitInt n = Lit (mkMachInt (toInteger n))
346
347 varToCoreExpr :: CoreBndr -> Expr b
348 varToCoreExpr v | isId v    = Var v
349                 | otherwise = Type (mkTyVarTy v)
350 \end{code}
351
352
353 %************************************************************************
354 %*                                                                      *
355 \subsection{Simple access functions}
356 %*                                                                      *
357 %************************************************************************
358
359 \begin{code}
360 bindersOf  :: Bind b -> [b]
361 bindersOf (NonRec binder _) = [binder]
362 bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
363
364 bindersOfBinds :: [Bind b] -> [b]
365 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
366
367 rhssOfBind :: Bind b -> [Expr b]
368 rhssOfBind (NonRec _ rhs) = [rhs]
369 rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
370
371 rhssOfAlts :: [Alt b] -> [Expr b]
372 rhssOfAlts alts = [e | (_,_,e) <- alts]
373
374 flattenBinds :: [Bind b] -> [(b, Expr b)]       -- Get all the lhs/rhs pairs
375 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
376 flattenBinds (Rec prs1   : binds) = prs1 ++ flattenBinds binds
377 flattenBinds []                   = []
378 \end{code}
379
380 We often want to strip off leading lambdas before getting down to
381 business.  @collectBinders@ is your friend.
382
383 We expect (by convention) type-, and value- lambdas in that
384 order.
385
386 \begin{code}
387 collectBinders               :: Expr b -> ([b],         Expr b)
388 collectBindersIgnoringNotes  :: Expr b -> ([b],         Expr b)
389 collectTyBinders             :: CoreExpr -> ([TyVar],     CoreExpr)
390 collectValBinders            :: CoreExpr -> ([Id],        CoreExpr)
391 collectTyAndValBinders       :: CoreExpr -> ([TyVar], [Id], CoreExpr)
392
393 collectBinders expr
394   = go [] expr
395   where
396     go bs (Lam b e) = go (b:bs) e
397     go bs e          = (reverse bs, e)
398
399 -- This one ignores notes.  It's used in CoreUnfold and StrAnal
400 -- when we aren't going to put the expression back together from
401 -- the pieces, so we don't mind losing the Notes
402 collectBindersIgnoringNotes expr
403   = go [] expr
404   where
405     go bs (Lam b e)  = go (b:bs) e
406     go bs (Note _ e) = go    bs  e
407     go bs e          = (reverse bs, e)
408
409 collectTyAndValBinders expr
410   = (tvs, ids, body)
411   where
412     (tvs, body1) = collectTyBinders expr
413     (ids, body)  = collectValBinders body1
414
415 collectTyBinders expr
416   = go [] expr
417   where
418     go tvs (Lam b e) | isTyVar b = go (b:tvs) e
419     go tvs e                     = (reverse tvs, e)
420
421 collectValBinders expr
422   = go [] expr
423   where
424     go ids (Lam b e) | isId b = go (b:ids) e
425     go ids body               = (reverse ids, body)
426 \end{code}
427
428
429 @collectArgs@ takes an application expression, returning the function
430 and the arguments to which it is applied.
431
432 \begin{code}
433 collectArgs :: Expr b -> (Expr b, [Arg b])
434 collectArgs expr
435   = go expr []
436   where
437     go (App f a) as = go f (a:as)
438     go e         as = (e, as)
439 \end{code}
440
441 coreExprCc gets the cost centre enclosing an expression, if any.
442 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
443
444 \begin{code}
445 coreExprCc :: Expr b -> CostCentre
446 coreExprCc (Note (SCC cc) e)   = cc
447 coreExprCc (Note other_note e) = coreExprCc e
448 coreExprCc (Lam _ e)           = coreExprCc e
449 coreExprCc other               = noCostCentre
450 \end{code}
451
452
453 %************************************************************************
454 %*                                                                      *
455 \subsection{Predicates}
456 %*                                                                      *
457 %************************************************************************
458
459 \begin{code}
460 isValArg (Type _) = False
461 isValArg other    = True
462
463 isTypeArg (Type _) = True
464 isTypeArg other    = False
465
466 valBndrCount :: [CoreBndr] -> Int
467 valBndrCount []                   = 0
468 valBndrCount (b : bs) | isId b    = 1 + valBndrCount bs
469                       | otherwise = valBndrCount bs
470
471 valArgCount :: [Arg b] -> Int
472 valArgCount []              = 0
473 valArgCount (Type _ : args) = valArgCount args
474 valArgCount (other  : args) = 1 + valArgCount args
475 \end{code}
476
477
478 %************************************************************************
479 %*                                                                      *
480 \subsection{Seq stuff}
481 %*                                                                      *
482 %************************************************************************
483
484 \begin{code}
485 seqExpr :: CoreExpr -> ()
486 seqExpr (Var v)       = v `seq` ()
487 seqExpr (Lit lit)     = lit `seq` ()
488 seqExpr (App f a)     = seqExpr f `seq` seqExpr a
489 seqExpr (Lam b e)     = seqBndr b `seq` seqExpr e
490 seqExpr (Let b e)     = seqBind b `seq` seqExpr e
491 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
492 seqExpr (Note n e)    = seqNote n `seq` seqExpr e
493 seqExpr (Type t)      = seqType t
494
495 seqExprs [] = ()
496 seqExprs (e:es) = seqExpr e `seq` seqExprs es
497
498 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
499 seqNote other          = ()
500
501 seqBndr b = b `seq` ()
502
503 seqBndrs [] = ()
504 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
505
506 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
507 seqBind (Rec prs)    = seqPairs prs
508
509 seqPairs [] = ()
510 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
511
512 seqAlts [] = ()
513 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
514
515 seqRules :: CoreRules -> ()
516 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
517
518 seq_rules [] = ()
519 seq_rules (Rule fs bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
520 seq_rules (BuiltinRule _ : rules) = seq_rules rules
521 \end{code}
522
523
524
525 %************************************************************************
526 %*                                                                      *
527 \subsection{Annotated core; annotation at every node in the tree}
528 %*                                                                      *
529 %************************************************************************
530
531 \begin{code}
532 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
533
534 data AnnExpr' bndr annot
535   = AnnVar      Id
536   | AnnLit      Literal
537   | AnnLam      bndr (AnnExpr bndr annot)
538   | AnnApp      (AnnExpr bndr annot) (AnnExpr bndr annot)
539   | AnnCase     (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
540   | AnnLet      (AnnBind bndr annot) (AnnExpr bndr annot)
541   | AnnNote     Note (AnnExpr bndr annot)
542   | AnnType     Type
543
544 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
545
546 data AnnBind bndr annot
547   = AnnNonRec bndr (AnnExpr bndr annot)
548   | AnnRec    [(bndr, AnnExpr bndr annot)]
549 \end{code}
550
551 \begin{code}
552 deAnnotate :: AnnExpr bndr annot -> Expr bndr
553 deAnnotate (_, e) = deAnnotate' e
554
555 deAnnotate' (AnnType t)           = Type t
556 deAnnotate' (AnnVar  v)           = Var v
557 deAnnotate' (AnnLit  lit)         = Lit lit
558 deAnnotate' (AnnLam  binder body) = Lam binder (deAnnotate body)
559 deAnnotate' (AnnApp  fun arg)     = App (deAnnotate fun) (deAnnotate arg)
560 deAnnotate' (AnnNote note body)   = Note note (deAnnotate body)
561
562 deAnnotate' (AnnLet bind body)
563   = Let (deAnnBind bind) (deAnnotate body)
564   where
565     deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
566     deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
567
568 deAnnotate' (AnnCase scrut v alts)
569   = Case (deAnnotate scrut) v (map deAnnAlt alts)
570   where
571     deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
572 \end{code}
573