[project @ 2000-11-14 10: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         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, deAnnotate, deAnnotate',
39
40         -- Core rules
41         CoreRules(..),  -- Representation needed by friends
42         CoreRule(..),   -- CoreSubst, CoreTidy, CoreFVs, PprCore only
43         IdCoreRule,
44         RuleName,
45         emptyCoreRules, isEmptyCoreRules, rulesRhsFreeVars, rulesRules,
46         isBuiltinRule
47     ) where
48
49 #include "HsVersions.h"
50
51 import CostCentre       ( CostCentre, noCostCentre )
52 import Var              ( Var, Id, TyVar, isTyVar, isId )
53 import Type             ( Type, mkTyVarTy, seqType )
54 import Literal          ( Literal, mkMachInt )
55 import DataCon          ( DataCon, dataConId )
56 import VarSet
57 import Outputable
58 \end{code}
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{The main data types}
63 %*                                                                      *
64 %************************************************************************
65
66 These data types are the heart of the compiler
67
68 \begin{code}
69 infixl 8 `App`  -- App brackets to the left
70
71 data Expr b     -- "b" for the type of binders, 
72   = Var   Id
73   | Lit   Literal
74   | App   (Expr b) (Arg b)
75   | Lam   b (Expr b)
76   | Let   (Bind b) (Expr b)
77   | Case  (Expr b) b [Alt b]    -- Binder gets bound to value of scrutinee
78                                 -- DEFAULT case must be last, if it occurs at all
79   | Note  Note (Expr b)
80   | Type  Type                  -- This should only show up at the top
81                                 -- level of an Arg
82
83 type Arg b = Expr b             -- Can be a Type
84
85 type Alt b = (AltCon, [b], Expr b)      -- (DEFAULT, [], rhs) is the default alternative
86
87 data AltCon = DataAlt DataCon
88             | LitAlt  Literal
89             | DEFAULT
90          deriving (Eq, Ord)
91
92 data Bind b = NonRec b (Expr b)
93               | Rec [(b, (Expr b))]
94
95 data Note
96   = SCC CostCentre
97
98   | Coerce      
99         Type            -- The to-type:   type of whole coerce expression
100         Type            -- The from-type: type of enclosed expression
101
102   | InlineCall          -- Instructs simplifier to inline
103                         -- the enclosed call
104
105   | InlineMe            -- Instructs simplifer to treat the enclosed expression
106                         -- as very small, and inline it at its call sites
107 \end{code}
108
109
110 %************************************************************************
111 %*                                                                      *
112 \subsection{Transformation rules}
113 %*                                                                      *
114 %************************************************************************
115
116 The CoreRule type and its friends are dealt with mainly in CoreRules,
117 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
118
119 \begin{code}
120 data CoreRules 
121   = Rules [CoreRule]
122           VarSet                -- Locally-defined free vars of RHSs
123
124 emptyCoreRules :: CoreRules
125 emptyCoreRules = Rules [] emptyVarSet
126
127 isEmptyCoreRules :: CoreRules -> Bool
128 isEmptyCoreRules (Rules rs _) = null rs
129
130 rulesRhsFreeVars :: CoreRules -> VarSet
131 rulesRhsFreeVars (Rules _ fvs) = fvs
132
133 rulesRules :: CoreRules -> [CoreRule]
134 rulesRules (Rules rules _) = rules
135 \end{code}
136
137 \begin{code}
138 type RuleName = FAST_STRING
139 type IdCoreRule = (Id,CoreRule)         -- Rules don't have their leading Id inside them
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
261 neverUnfold :: Unfolding -> Bool
262 neverUnfold NoUnfolding                         = True
263 neverUnfold (OtherCon _)                        = True
264 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
265 neverUnfold other                               = False
266 \end{code}
267
268
269 %************************************************************************
270 %*                                                                      *
271 \subsection{The main data type}
272 %*                                                                      *
273 %************************************************************************
274
275 \begin{code}
276 -- The Ord is needed for the FiniteMap used in the lookForConstructor
277 -- in SimplEnv.  If you declared that lookForConstructor *ignores*
278 -- constructor-applications with LitArg args, then you could get
279 -- rid of this Ord.
280
281 instance Outputable AltCon where
282   ppr (DataAlt dc) = ppr dc
283   ppr (LitAlt lit) = ppr lit
284   ppr DEFAULT      = ptext SLIT("__DEFAULT")
285
286 instance Show AltCon where
287   showsPrec p con = showsPrecSDoc p (ppr con)
288 \end{code}
289
290
291 %************************************************************************
292 %*                                                                      *
293 \subsection{Useful synonyms}
294 %*                                                                      *
295 %************************************************************************
296
297 The common case
298
299 \begin{code}
300 type CoreBndr = Var
301 type CoreExpr = Expr CoreBndr
302 type CoreArg  = Arg  CoreBndr
303 type CoreBind = Bind CoreBndr
304 type CoreAlt  = Alt  CoreBndr
305 \end{code}
306
307 Binders are ``tagged'' with a \tr{t}:
308
309 \begin{code}
310 type Tagged t = (CoreBndr, t)
311
312 type TaggedBind t = Bind (Tagged t)
313 type TaggedExpr t = Expr (Tagged t)
314 type TaggedArg  t = Arg  (Tagged t)
315 type TaggedAlt  t = Alt  (Tagged t)
316 \end{code}
317
318
319 %************************************************************************
320 %*                                                                      *
321 \subsection{Core-constructing functions with checking}
322 %*                                                                      *
323 %************************************************************************
324
325 \begin{code}
326 mkApps    :: Expr b -> [Arg b]  -> Expr b
327 mkTyApps  :: Expr b -> [Type]   -> Expr b
328 mkValApps :: Expr b -> [Expr b] -> Expr b
329 mkVarApps :: Expr b -> [Var] -> Expr b
330
331 mkApps    f args = foldl App                       f args
332 mkTyApps  f args = foldl (\ e a -> App e (Type a)) f args
333 mkValApps f args = foldl (\ e a -> App e a)        f args
334 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
335
336 mkLit         :: Literal -> Expr b
337 mkIntLit      :: Integer -> Expr b
338 mkIntLitInt   :: Int     -> Expr b
339 mkConApp      :: DataCon -> [Arg b] -> Expr b
340 mkLets        :: [Bind b] -> Expr b -> Expr b
341 mkLams        :: [b] -> Expr b -> Expr b
342
343 mkLit lit         = Lit lit
344 mkConApp con args = mkApps (Var (dataConId con)) args
345
346 mkLams binders body = foldr Lam body binders
347 mkLets binds body   = foldr Let body binds
348
349 mkIntLit    n = Lit (mkMachInt n)
350 mkIntLitInt n = Lit (mkMachInt (toInteger n))
351
352 varToCoreExpr :: CoreBndr -> Expr b
353 varToCoreExpr v | isId v    = Var v
354                 | otherwise = Type (mkTyVarTy v)
355 \end{code}
356
357
358 %************************************************************************
359 %*                                                                      *
360 \subsection{Simple access functions}
361 %*                                                                      *
362 %************************************************************************
363
364 \begin{code}
365 bindersOf  :: Bind b -> [b]
366 bindersOf (NonRec binder _) = [binder]
367 bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
368
369 bindersOfBinds :: [Bind b] -> [b]
370 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
371
372 rhssOfBind :: Bind b -> [Expr b]
373 rhssOfBind (NonRec _ rhs) = [rhs]
374 rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
375
376 rhssOfAlts :: [Alt b] -> [Expr b]
377 rhssOfAlts alts = [e | (_,_,e) <- alts]
378
379 flattenBinds :: [Bind b] -> [(b, Expr b)]       -- Get all the lhs/rhs pairs
380 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
381 flattenBinds (Rec prs1   : binds) = prs1 ++ flattenBinds binds
382 flattenBinds []                   = []
383 \end{code}
384
385 We often want to strip off leading lambdas before getting down to
386 business.  @collectBinders@ is your friend.
387
388 We expect (by convention) type-, and value- lambdas in that
389 order.
390
391 \begin{code}
392 collectBinders               :: Expr b -> ([b],         Expr b)
393 collectBindersIgnoringNotes  :: Expr b -> ([b],         Expr b)
394 collectTyBinders             :: CoreExpr -> ([TyVar],     CoreExpr)
395 collectValBinders            :: CoreExpr -> ([Id],        CoreExpr)
396 collectTyAndValBinders       :: CoreExpr -> ([TyVar], [Id], CoreExpr)
397
398 collectBinders expr
399   = go [] expr
400   where
401     go bs (Lam b e) = go (b:bs) e
402     go bs e          = (reverse bs, e)
403
404 -- This one ignores notes.  It's used in CoreUnfold and StrAnal
405 -- when we aren't going to put the expression back together from
406 -- the pieces, so we don't mind losing the Notes
407 collectBindersIgnoringNotes expr
408   = go [] expr
409   where
410     go bs (Lam b e)  = go (b:bs) e
411     go bs (Note _ e) = go    bs  e
412     go bs e          = (reverse bs, e)
413
414 collectTyAndValBinders expr
415   = (tvs, ids, body)
416   where
417     (tvs, body1) = collectTyBinders expr
418     (ids, body)  = collectValBinders body1
419
420 collectTyBinders expr
421   = go [] expr
422   where
423     go tvs (Lam b e) | isTyVar b = go (b:tvs) e
424     go tvs e                     = (reverse tvs, e)
425
426 collectValBinders expr
427   = go [] expr
428   where
429     go ids (Lam b e) | isId b = go (b:ids) e
430     go ids body               = (reverse ids, body)
431 \end{code}
432
433
434 @collectArgs@ takes an application expression, returning the function
435 and the arguments to which it is applied.
436
437 \begin{code}
438 collectArgs :: Expr b -> (Expr b, [Arg b])
439 collectArgs expr
440   = go expr []
441   where
442     go (App f a) as = go f (a:as)
443     go e         as = (e, as)
444 \end{code}
445
446 coreExprCc gets the cost centre enclosing an expression, if any.
447 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
448
449 \begin{code}
450 coreExprCc :: Expr b -> CostCentre
451 coreExprCc (Note (SCC cc) e)   = cc
452 coreExprCc (Note other_note e) = coreExprCc e
453 coreExprCc (Lam _ e)           = coreExprCc e
454 coreExprCc other               = noCostCentre
455 \end{code}
456
457
458 %************************************************************************
459 %*                                                                      *
460 \subsection{Predicates}
461 %*                                                                      *
462 %************************************************************************
463
464 \begin{code}
465 isValArg (Type _) = False
466 isValArg other    = True
467
468 isTypeArg (Type _) = True
469 isTypeArg other    = False
470
471 valBndrCount :: [CoreBndr] -> Int
472 valBndrCount []                   = 0
473 valBndrCount (b : bs) | isId b    = 1 + valBndrCount bs
474                       | otherwise = valBndrCount bs
475
476 valArgCount :: [Arg b] -> Int
477 valArgCount []              = 0
478 valArgCount (Type _ : args) = valArgCount args
479 valArgCount (other  : args) = 1 + valArgCount args
480 \end{code}
481
482
483 %************************************************************************
484 %*                                                                      *
485 \subsection{Seq stuff}
486 %*                                                                      *
487 %************************************************************************
488
489 \begin{code}
490 seqExpr :: CoreExpr -> ()
491 seqExpr (Var v)       = v `seq` ()
492 seqExpr (Lit lit)     = lit `seq` ()
493 seqExpr (App f a)     = seqExpr f `seq` seqExpr a
494 seqExpr (Lam b e)     = seqBndr b `seq` seqExpr e
495 seqExpr (Let b e)     = seqBind b `seq` seqExpr e
496 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
497 seqExpr (Note n e)    = seqNote n `seq` seqExpr e
498 seqExpr (Type t)      = seqType t
499
500 seqExprs [] = ()
501 seqExprs (e:es) = seqExpr e `seq` seqExprs es
502
503 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
504 seqNote other          = ()
505
506 seqBndr b = b `seq` ()
507
508 seqBndrs [] = ()
509 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
510
511 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
512 seqBind (Rec prs)    = seqPairs prs
513
514 seqPairs [] = ()
515 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
516
517 seqAlts [] = ()
518 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
519
520 seqRules :: CoreRules -> ()
521 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
522
523 seq_rules [] = ()
524 seq_rules (Rule fs bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
525 seq_rules (BuiltinRule _ : rules) = seq_rules rules
526 \end{code}
527
528
529
530 %************************************************************************
531 %*                                                                      *
532 \subsection{Annotated core; annotation at every node in the tree}
533 %*                                                                      *
534 %************************************************************************
535
536 \begin{code}
537 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
538
539 data AnnExpr' bndr annot
540   = AnnVar      Id
541   | AnnLit      Literal
542   | AnnLam      bndr (AnnExpr bndr annot)
543   | AnnApp      (AnnExpr bndr annot) (AnnExpr bndr annot)
544   | AnnCase     (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
545   | AnnLet      (AnnBind bndr annot) (AnnExpr bndr annot)
546   | AnnNote     Note (AnnExpr bndr annot)
547   | AnnType     Type
548
549 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
550
551 data AnnBind bndr annot
552   = AnnNonRec bndr (AnnExpr bndr annot)
553   | AnnRec    [(bndr, AnnExpr bndr annot)]
554 \end{code}
555
556 \begin{code}
557 deAnnotate :: AnnExpr bndr annot -> Expr bndr
558 deAnnotate (_, e) = deAnnotate' e
559
560 deAnnotate' (AnnType t)           = Type t
561 deAnnotate' (AnnVar  v)           = Var v
562 deAnnotate' (AnnLit  lit)         = Lit lit
563 deAnnotate' (AnnLam  binder body) = Lam binder (deAnnotate body)
564 deAnnotate' (AnnApp  fun arg)     = App (deAnnotate fun) (deAnnotate arg)
565 deAnnotate' (AnnNote note body)   = Note note (deAnnotate body)
566
567 deAnnotate' (AnnLet bind body)
568   = Let (deAnnBind bind) (deAnnotate body)
569   where
570     deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
571     deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
572
573 deAnnotate' (AnnCase scrut v alts)
574   = Case (deAnnotate scrut) v (map deAnnAlt alts)
575   where
576     deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
577 \end{code}
578