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