root/compiler/coreSyn/CoreSyn.lhs

Revision 1cec00dbb87051b4df159ee06c11516bf49ff109, 52.5 KB (checked in by Simon Peyton Jones <simonpj@…>, 3 weeks ago)

Merge branch 'master' of  http://darcs.haskell.org//ghc

  • Property mode set to 100644
Line 
1%
2% (c) The University of Glasgow 2006
3% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4%
5
6\begin{code}
7{-# LANGUAGE DeriveDataTypeable, DeriveFunctor #-}
8
9{-# OPTIONS -fno-warn-tabs #-}
10-- The above warning supression flag is a temporary kludge.
11-- While working on this module you are encouraged to remove it and
12-- detab the module (please do the detabbing in a separate patch). See
13--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
14-- for details
15
16-- | CoreSyn holds all the main data types for use by for the Glasgow Haskell Compiler midsection
17module CoreSyn (
18        -- * Main data types
19        Expr(..), Alt, Bind(..), AltCon(..), Arg, Tickish(..),
20        CoreProgram, CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
21        TaggedExpr, TaggedAlt, TaggedBind, TaggedArg, TaggedBndr(..),
22
23        -- ** 'Expr' construction
24        mkLets, mkLams,
25        mkApps, mkTyApps, mkCoApps, mkVarApps,
26       
27        mkIntLit, mkIntLitInt,
28        mkWordLit, mkWordLitWord,
29        mkWord64LitWord64, mkInt64LitInt64,
30        mkCharLit, mkStringLit,
31        mkFloatLit, mkFloatLitFloat,
32        mkDoubleLit, mkDoubleLitDouble,
33       
34        mkConApp, mkTyBind, mkCoBind,
35        varToCoreExpr, varsToCoreExprs,
36
37        isId, cmpAltCon, cmpAlt, ltAlt,
38       
39        -- ** Simple 'Expr' access functions and predicates
40        bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts, 
41        collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
42        collectArgs, flattenBinds,
43
44        isValArg, isTypeArg, isTyCoArg, valArgCount, valBndrCount,
45        isRuntimeArg, isRuntimeVar,
46
47        tickishCounts, tickishScoped, tickishIsCode, mkNoTick, mkNoScope,
48        tickishCanSplit,
49
50        -- * Unfolding data types
51        Unfolding(..),  UnfoldingGuidance(..), UnfoldingSource(..),
52
53        -- ** Constructing 'Unfolding's
54        noUnfolding, evaldUnfolding, mkOtherCon,
55        unSaturatedOk, needSaturated, boringCxtOk, boringCxtNotOk,
56       
57        -- ** Predicates and deconstruction on 'Unfolding'
58        unfoldingTemplate, setUnfoldingTemplate, expandUnfolding_maybe,
59        maybeUnfoldingTemplate, otherCons, unfoldingArity,
60        isValueUnfolding, isEvaldUnfolding, isCheapUnfolding,
61        isExpandableUnfolding, isConLikeUnfolding, isCompulsoryUnfolding,
62        isStableUnfolding, isStableCoreUnfolding_maybe,
63        isClosedUnfolding, hasSomeUnfolding, 
64        canUnfold, neverUnfoldGuidance, isStableSource,
65
66        -- * Strictness
67        seqExpr, seqExprs, seqUnfolding, 
68
69        -- * Annotated expression data types
70        AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
71       
72        -- ** Operations on annotated expressions
73        collectAnnArgs,
74
75        -- ** Operations on annotations
76        deAnnotate, deAnnotate', deAnnAlt, collectAnnBndrs,
77
78        -- * Core rule data types
79        CoreRule(..),   -- CoreSubst, CoreTidy, CoreFVs, PprCore only
80        RuleName, IdUnfoldingFun,
81       
82        -- ** Operations on 'CoreRule's 
83        seqRules, ruleArity, ruleName, ruleIdName, ruleActivation,
84        setRuleIdName,
85        isBuiltinRule, isLocalRule,
86
87        -- * Core vectorisation declarations data type
88        CoreVect(..)
89    ) where
90
91#include "HsVersions.h"
92
93import CostCentre
94import Var
95import Type
96import Coercion
97import Name
98import Literal
99import DataCon
100import Module
101import TyCon
102import BasicTypes
103import FastString
104import Outputable
105import Util
106
107import Data.Data hiding (TyCon)
108import Data.Int
109import Data.Word
110
111infixl 4 `mkApps`, `mkTyApps`, `mkVarApps`, `App`, `mkCoApps`
112-- Left associative, so that we can say (f `mkTyApps` xs `mkVarApps` ys)
113\end{code}
114
115%************************************************************************
116%*                                                                      *
117\subsection{The main data types}
118%*                                                                      *
119%************************************************************************
120
121These data types are the heart of the compiler
122
123\begin{code}
124-- | This is the data type that represents GHCs core intermediate language. Currently
125-- GHC uses System FC <http://research.microsoft.com/~simonpj/papers/ext-f/> for this purpose,
126-- which is closely related to the simpler and better known System F <http://en.wikipedia.org/wiki/System_F>.
127--
128-- We get from Haskell source to this Core language in a number of stages:
129--
130-- 1. The source code is parsed into an abstract syntax tree, which is represented
131--    by the data type 'HsExpr.HsExpr' with the names being 'RdrName.RdrNames'
132--
133-- 2. This syntax tree is /renamed/, which attaches a 'Unique.Unique' to every 'RdrName.RdrName'
134--    (yielding a 'Name.Name') to disambiguate identifiers which are lexically identical.
135--    For example, this program:
136--
137-- @
138--      f x = let f x = x + 1
139--            in f (x - 2)
140-- @
141--
142--    Would be renamed by having 'Unique's attached so it looked something like this:
143--
144-- @
145--      f_1 x_2 = let f_3 x_4 = x_4 + 1
146--                in f_3 (x_2 - 2)
147-- @
148--
149-- 3. The resulting syntax tree undergoes type checking (which also deals with instantiating
150--    type class arguments) to yield a 'HsExpr.HsExpr' type that has 'Id.Id' as it's names.
151--
152-- 4. Finally the syntax tree is /desugared/ from the expressive 'HsExpr.HsExpr' type into
153--    this 'Expr' type, which has far fewer constructors and hence is easier to perform
154--    optimization, analysis and code generation on.
155--
156-- The type parameter @b@ is for the type of binders in the expression tree.
157--
158-- The language consists of the following elements:
159--
160-- *  Variables
161--
162-- *  Primitive literals
163--
164-- *  Applications: note that the argument may be a 'Type'.
165--
166--    See "CoreSyn#let_app_invariant" for another invariant
167--
168-- *  Lambda abstraction
169--
170-- *  Recursive and non recursive @let@s. Operationally
171--    this corresponds to allocating a thunk for the things
172--    bound and then executing the sub-expression.
173--   
174--    #top_level_invariant#
175--    #letrec_invariant#
176--   
177--    The right hand sides of all top-level and recursive @let@s
178--    /must/ be of lifted type (see "Type#type_classification" for
179--    the meaning of /lifted/ vs. /unlifted/).
180--   
181--    #let_app_invariant#
182--    The right hand side of of a non-recursive 'Let'
183--    _and_ the argument of an 'App',
184--    /may/ be of unlifted type, but only if the expression
185--    is ok-for-speculation.  This means that the let can be floated
186--    around without difficulty. For example, this is OK:
187--   
188--    > y::Int# = x +# 1#
189--   
190--    But this is not, as it may affect termination if the
191--    expression is floated out:
192--   
193--    > y::Int# = fac 4#
194--   
195--    In this situation you should use @case@ rather than a @let@. The function
196--    'CoreUtils.needsCaseBinding' can help you determine which to generate, or
197--    alternatively use 'MkCore.mkCoreLet' rather than this constructor directly,
198--    which will generate a @case@ if necessary
199--   
200--    #type_let#
201--    We allow a /non-recursive/ let to bind a type variable, thus:
202--   
203--    > Let (NonRec tv (Type ty)) body
204--   
205--    This can be very convenient for postponing type substitutions until
206--    the next run of the simplifier.
207--   
208--    At the moment, the rest of the compiler only deals with type-let
209--    in a Let expression, rather than at top level.  We may want to revist
210--    this choice.
211--
212-- *  Case split. Operationally this corresponds to evaluating
213--    the scrutinee (expression examined) to weak head normal form
214--    and then examining at most one level of resulting constructor (i.e. you
215--    cannot do nested pattern matching directly with this).
216--   
217--    The binder gets bound to the value of the scrutinee,
218--    and the 'Type' must be that of all the case alternatives
219--   
220--    #case_invariants#
221--    This is one of the more complicated elements of the Core language,
222--    and comes with a number of restrictions:
223--   
224--    1. The list of alternatives may be empty;
225--       See Note [Empty case alternatives]
226--
227--    2. The 'DEFAULT' case alternative must be first in the list,
228--       if it occurs at all.
229--   
230--    3. The remaining cases are in order of increasing
231--         tag  (for 'DataAlts') or
232--         lit  (for 'LitAlts').
233--       This makes finding the relevant constructor easy,
234--       and makes comparison easier too.
235--   
236--    4. The list of alternatives must be exhaustive. An /exhaustive/ case
237--       does not necessarily mention all constructors:
238--   
239--       @
240--            data Foo = Red | Green | Blue
241--       ... case x of
242--            Red   -> True
243--            other -> f (case x of
244--                            Green -> ...
245--                            Blue  -> ... ) ...
246--       @
247--   
248--       The inner case does not need a @Red@ alternative, because @x@
249--       can't be @Red@ at that program point.
250--
251-- *  Cast an expression to a particular type.
252--    This is used to implement @newtype@s (a @newtype@ constructor or
253--    destructor just becomes a 'Cast' in Core) and GADTs.
254--
255-- *  Notes. These allow general information to be added to expressions
256--    in the syntax tree
257--
258-- *  A type: this should only show up at the top level of an Arg
259--
260-- *  A coercion
261data Expr b
262  = Var   Id
263  | Lit   Literal
264  | App   (Expr b) (Arg b)
265  | Lam   b (Expr b)
266  | Let   (Bind b) (Expr b)
267  | Case  (Expr b) b Type [Alt b]       -- See #case_invariant#
268  | Cast  (Expr b) Coercion
269  | Tick  (Tickish Id) (Expr b)
270  | Type  Type
271  | Coercion Coercion
272  deriving (Data, Typeable)
273
274-- | Type synonym for expressions that occur in function argument positions.
275-- Only 'Arg' should contain a 'Type' at top level, general 'Expr' should not
276type Arg b = Expr b
277
278-- | A case split alternative. Consists of the constructor leading to the alternative,
279-- the variables bound from the constructor, and the expression to be executed given that binding.
280-- The default alternative is @(DEFAULT, [], rhs)@
281type Alt b = (AltCon, [b], Expr b)
282
283-- | A case alternative constructor (i.e. pattern match)
284data AltCon 
285  = DataAlt DataCon   --  ^ A plain data constructor: @case e of { Foo x -> ... }@.
286                      -- Invariant: the 'DataCon' is always from a @data@ type, and never from a @newtype@
287
288  | LitAlt  Literal   -- ^ A literal: @case e of { 1 -> ... }@
289                      -- Invariant: always an *unlifted* literal
290                      -- See Note [Literal alternatives]
291                     
292  | DEFAULT           -- ^ Trivial alternative: @case e of { _ -> ... }@
293   deriving (Eq, Ord, Data, Typeable)
294
295-- | Binding, used for top level bindings in a module and local bindings in a @let@.
296data Bind b = NonRec b (Expr b)
297            | Rec [(b, (Expr b))]
298  deriving (Data, Typeable)
299\end{code}
300
301Note [Literal alternatives]
302~~~~~~~~~~~~~~~~~~~~~~~~~~~
303Literal alternatives (LitAlt lit) are always for *un-lifted* literals.
304We have one literal, a literal Integer, that is lifted, and we don't
305allow in a LitAlt, because LitAlt cases don't do any evaluation. Also
306(see Trac #5603) if you say
307    case 3 of
308      S# x -> ...
309      J# _ _ -> ...
310(where S#, J# are the constructors for Integer) we don't want the
311simplifier calling findAlt with argument (LitAlt 3).  No no.  Integer
312literals are an opaque encoding of an algebraic data type, not of
313an unlifted literal, like all the others.
314
315
316-------------------------- CoreSyn INVARIANTS ---------------------------
317
318Note [CoreSyn top-level invariant]
319~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
320See #toplevel_invariant#
321
322Note [CoreSyn letrec invariant]
323~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
324See #letrec_invariant#
325
326Note [CoreSyn let/app invariant]
327~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
328See #let_app_invariant#
329
330This is intially enforced by DsUtils.mkCoreLet and mkCoreApp
331
332Note [CoreSyn case invariants]
333~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
334See #case_invariants#
335
336Note [CoreSyn let goal]
337~~~~~~~~~~~~~~~~~~~~~~~
338* The simplifier tries to ensure that if the RHS of a let is a constructor
339  application, its arguments are trivial, so that the constructor can be
340  inlined vigorously.
341
342Note [Type let]
343~~~~~~~~~~~~~~~
344See #type_let#
345
346Note [Empty case alternatives]
347~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
348The alternatives of a case expression should be exhaustive.  A case expression
349can have empty alternatives if (and only if) the scrutinee is bound to raise
350an exception or diverge.  So:
351   Case (error Int "Hello") b Bool []
352is fine, and has type Bool.  This is one reason we need a type on
353the case expression: if the alternatives are empty we can't get the type
354from the alternatives!  I'll write this
355   case (error Int "Hello") of Bool {}
356with the return type just before the alterantives.
357
358Here's another example:
359  data T
360  f :: T -> Bool
361  f = \(x:t). case x of Bool {}
362Since T has no data constructors, the case alterantives are of course
363empty.  However note that 'x' is not bound to a visbily-bottom value;
364it's the *type* that tells us it's going to diverge.  Its a bit of a
365degnerate situation but we do NOT want to replace
366   case x of Bool {}   -->   error Bool "Inaccessible case"
367because x might raise an exception, and *that*'s what we want to see!
368(Trac #6067 is an example.) To preserve semantics we'd have to say
369   x `seq` error Bool "Inaccessible case"   
370 but the 'seq' is just a case, so we are back to square 1.  Or I suppose
371we could say
372   x |> UnsafeCoerce T Bool
373but that loses all trace of the fact that this originated with an empty
374set of alternatives.
375
376We can use the empty-alternative construct to coerce error values from
377one type to another.  For example
378
379    f :: Int -> Int
380    f n = error "urk"
381   
382    g :: Int -> (# Char, Bool #)
383    g x = case f x of { 0 -> ..., n -> ... }
384
385Then if we inline f in g's RHS we get
386    case (error Int "urk") of (# Char, Bool #) { ... }
387and we can discard the alternatives since the scrutinee is bottom to give
388    case (error Int "urk") of (# Char, Bool #) {}
389
390This is nicer than using an unsafe coerce between Int ~ (# Char,Bool #),
391if for no other reason that we don't need to instantiate the (~) at an
392unboxed type.
393
394
395%************************************************************************
396%*                                                                      *
397              Ticks
398%*                                                                      *
399%************************************************************************
400
401\begin{code}
402-- | Allows attaching extra information to points in expressions
403data Tickish id =
404    -- | An @{-# SCC #-}@ profiling annotation, either automatically
405    -- added by the desugarer as a result of -auto-all, or added by
406    -- the user.
407    ProfNote {
408      profNoteCC    :: CostCentre, -- ^ the cost centre
409      profNoteCount :: !Bool,      -- ^ bump the entry count?
410      profNoteScope :: !Bool       -- ^ scopes over the enclosed expression
411                                   -- (i.e. not just a tick)
412    }
413
414  -- | A "tick" used by HPC to track the execution of each
415  -- subexpression in the original source code.
416  | HpcTick {
417      tickModule :: Module,
418      tickId     :: !Int
419    }
420
421  -- | A breakpoint for the GHCi debugger.  This behaves like an HPC
422  -- tick, but has a list of free variables which will be available
423  -- for inspection in GHCi when the program stops at the breakpoint.
424  --
425  -- NB. we must take account of these Ids when (a) counting free variables,
426  -- and (b) substituting (don't substitute for them)
427  | Breakpoint
428    { breakpointId     :: !Int
429    , breakpointFVs    :: [id]  -- ^ the order of this list is important:
430                                -- it matches the order of the lists in the
431                                -- appropriate entry in HscTypes.ModBreaks.
432                                --
433                                -- Careful about substitution!  See
434                                -- Note [substTickish] in CoreSubst.
435    }
436
437  deriving (Eq, Ord, Data, Typeable)
438
439
440-- | A "tick" note is one that counts evaluations in some way.  We
441-- cannot discard a tick, and the compiler should preserve the number
442-- of ticks as far as possible.
443--
444-- Hwever, we stil allow the simplifier to increase or decrease
445-- sharing, so in practice the actual number of ticks may vary, except
446-- that we never change the value from zero to non-zero or vice versa.
447--
448tickishCounts :: Tickish id -> Bool
449tickishCounts n@ProfNote{} = profNoteCount n
450tickishCounts HpcTick{}    = True
451tickishCounts Breakpoint{} = True
452
453tickishScoped :: Tickish id -> Bool
454tickishScoped n@ProfNote{} = profNoteScope n
455tickishScoped HpcTick{}    = False
456tickishScoped Breakpoint{} = True
457   -- Breakpoints are scoped: eventually we're going to do call
458   -- stacks, but also this helps prevent the simplifier from moving
459   -- breakpoints around and changing their result type (see #1531).
460
461mkNoTick :: Tickish id -> Tickish id
462mkNoTick n@ProfNote{} = n {profNoteCount = False}
463mkNoTick Breakpoint{} = panic "mkNoTick: Breakpoint" -- cannot split a BP
464mkNoTick t = t
465
466mkNoScope :: Tickish id -> Tickish id
467mkNoScope n@ProfNote{} = n {profNoteScope = False}
468mkNoScope Breakpoint{} = panic "mkNoScope: Breakpoint" -- cannot split a BP
469mkNoScope t = t
470
471-- | Return True if this source annotation compiles to some code, or will
472-- disappear before the backend.
473tickishIsCode :: Tickish id -> Bool
474tickishIsCode _tickish = True  -- all of them for now
475
476-- | Return True if this Tick can be split into (tick,scope) parts with
477-- 'mkNoScope' and 'mkNoTick' respectively.
478tickishCanSplit :: Tickish Id -> Bool
479tickishCanSplit Breakpoint{} = False
480tickishCanSplit _ = True
481\end{code}
482
483
484%************************************************************************
485%*                                                                      *
486\subsection{Transformation rules}
487%*                                                                      *
488%************************************************************************
489
490The CoreRule type and its friends are dealt with mainly in CoreRules,
491but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
492
493\begin{code}
494-- | A 'CoreRule' is:
495--
496-- * \"Local\" if the function it is a rule for is defined in the
497--   same module as the rule itself.
498--
499-- * \"Orphan\" if nothing on the LHS is defined in the same module
500--   as the rule itself
501data CoreRule
502  = Rule { 
503        ru_name :: RuleName,            -- ^ Name of the rule, for communication with the user
504        ru_act  :: Activation,          -- ^ When the rule is active
505
506        -- Rough-matching stuff
507        -- see comments with InstEnv.ClsInst( is_cls, is_rough )
508        ru_fn    :: Name,               -- ^ Name of the 'Id.Id' at the head of this rule
509        ru_rough :: [Maybe Name],       -- ^ Name at the head of each argument to the left hand side
510       
511        -- Proper-matching stuff
512        -- see comments with InstEnv.ClsInst( is_tvs, is_tys )
513        ru_bndrs :: [CoreBndr],         -- ^ Variables quantified over
514        ru_args  :: [CoreExpr],         -- ^ Left hand side arguments
515       
516        -- And the right-hand side
517        ru_rhs   :: CoreExpr,           -- ^ Right hand side of the rule
518                                        -- Occurrence info is guaranteed correct
519                                        -- See Note [OccInfo in unfoldings and rules]
520
521        -- Locality
522        ru_auto :: Bool,        -- ^ @True@  <=> this rule is auto-generated
523                                --   @False@ <=> generated at the users behest
524                                --   Main effect: reporting of orphan-hood
525
526        ru_local :: Bool        -- ^ @True@ iff the fn at the head of the rule is
527                                -- defined in the same module as the rule
528                                -- and is not an implicit 'Id' (like a record selector,
529                                -- class operation, or data constructor)
530
531                -- NB: ru_local is *not* used to decide orphan-hood
532                --      c.g. MkIface.coreRuleToIfaceRule
533    }
534
535  -- | Built-in rules are used for constant folding
536  -- and suchlike.  They have no free variables.
537  | BuiltinRule {               
538        ru_name  :: RuleName,   -- ^ As above
539        ru_fn    :: Name,       -- ^ As above
540        ru_nargs :: Int,        -- ^ Number of arguments that 'ru_try' consumes,
541                                -- if it fires, including type arguments
542        ru_try  :: IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
543                -- ^ This function does the rewrite.  It given too many
544                -- arguments, it simply discards them; the returned 'CoreExpr'
545                -- is just the rewrite of 'ru_fn' applied to the first 'ru_nargs' args
546    }
547                -- See Note [Extra args in rule matching] in Rules.lhs
548
549type IdUnfoldingFun = Id -> Unfolding
550-- A function that embodies how to unfold an Id if you need
551-- to do that in the Rule.  The reason we need to pass this info in
552-- is that whether an Id is unfoldable depends on the simplifier phase
553
554isBuiltinRule :: CoreRule -> Bool
555isBuiltinRule (BuiltinRule {}) = True
556isBuiltinRule _                = False
557
558-- | The number of arguments the 'ru_fn' must be applied
559-- to before the rule can match on it
560ruleArity :: CoreRule -> Int
561ruleArity (BuiltinRule {ru_nargs = n}) = n
562ruleArity (Rule {ru_args = args})      = length args
563
564ruleName :: CoreRule -> RuleName
565ruleName = ru_name
566
567ruleActivation :: CoreRule -> Activation
568ruleActivation (BuiltinRule { })       = AlwaysActive
569ruleActivation (Rule { ru_act = act }) = act
570
571-- | The 'Name' of the 'Id.Id' at the head of the rule left hand side
572ruleIdName :: CoreRule -> Name
573ruleIdName = ru_fn
574
575isLocalRule :: CoreRule -> Bool
576isLocalRule = ru_local
577
578-- | Set the 'Name' of the 'Id.Id' at the head of the rule left hand side
579setRuleIdName :: Name -> CoreRule -> CoreRule
580setRuleIdName nm ru = ru { ru_fn = nm }
581\end{code}
582
583
584%************************************************************************
585%*                                                                      *
586\subsection{Vectorisation declarations}
587%*                                                                      *
588%************************************************************************
589
590Representation of desugared vectorisation declarations that are fed to the vectoriser (via
591'ModGuts').
592
593\begin{code}
594data CoreVect = Vect      Id   (Maybe CoreExpr)
595              | NoVect    Id
596              | VectType  Bool TyCon (Maybe TyCon)
597              | VectClass TyCon                     -- class tycon
598              | VectInst  Id                        -- instance dfun (always SCALAR)
599\end{code}
600
601
602%************************************************************************
603%*                                                                      *
604                Unfoldings
605%*                                                                      *
606%************************************************************************
607
608The @Unfolding@ type is declared here to avoid numerous loops
609
610\begin{code}
611-- | Records the /unfolding/ of an identifier, which is approximately the form the
612-- identifier would have if we substituted its definition in for the identifier.
613-- This type should be treated as abstract everywhere except in "CoreUnfold"
614data Unfolding
615  = NoUnfolding        -- ^ We have no information about the unfolding
616
617  | OtherCon [AltCon]  -- ^ It ain't one of these constructors.
618                       -- @OtherCon xs@ also indicates that something has been evaluated
619                       -- and hence there's no point in re-evaluating it.
620                       -- @OtherCon []@ is used even for non-data-type values
621                       -- to indicated evaluated-ness.  Notably:
622                       --
623                       -- > data C = C !(Int -> Int)
624                       -- > case x of { C f -> ... }
625                       --
626                       -- Here, @f@ gets an @OtherCon []@ unfolding.
627
628  | DFunUnfolding       -- The Unfolding of a DFunId 
629                        -- See Note [DFun unfoldings]
630                        --     df = /\a1..am. \d1..dn. MkD (op1 a1..am d1..dn)
631                        --                                 (op2 a1..am d1..dn)
632
633        Arity           -- Arity = m+n, the *total* number of args
634                        --   (unusually, both type and value) to the dfun
635
636        DataCon         -- The dictionary data constructor (possibly a newtype datacon)
637
638        [CoreExpr]      -- Specification of superclasses and methods, in positional order
639
640  | CoreUnfolding {             -- An unfolding for an Id with no pragma,
641                                -- or perhaps a NOINLINE pragma
642                                -- (For NOINLINE, the phase, if any, is in the
643                                -- InlinePragInfo for this Id.)
644        uf_tmpl       :: CoreExpr,        -- Template; occurrence info is correct
645        uf_src        :: UnfoldingSource, -- Where the unfolding came from
646        uf_is_top     :: Bool,          -- True <=> top level binding
647        uf_arity      :: Arity,         -- Number of value arguments expected
648        uf_is_value   :: Bool,          -- exprIsHNF template (cached); it is ok to discard
649                                        --      a `seq` on this variable
650        uf_is_conlike :: Bool,          -- True <=> applicn of constructor or CONLIKE function
651                                        --      Cached version of exprIsConLike
652        uf_is_work_free :: Bool,                -- True <=> doesn't waste (much) work to expand
653                                        --          inside an inlining
654                                        --      Cached version of exprIsCheap
655        uf_expandable :: Bool,          -- True <=> can expand in RULE matching
656                                        --      Cached version of exprIsExpandable
657        uf_guidance   :: UnfoldingGuidance      -- Tells about the *size* of the template.
658    }
659  -- ^ An unfolding with redundant cached information. Parameters:
660  --
661  --  uf_tmpl: Template used to perform unfolding;
662  --           NB: Occurrence info is guaranteed correct:
663  --               see Note [OccInfo in unfoldings and rules]
664  --
665  --  uf_is_top: Is this a top level binding?
666  --
667  --  uf_is_value: 'exprIsHNF' template (cached); it is ok to discard a 'seq' on
668  --     this variable
669  --
670  --  uf_is_work_free:  Does this waste only a little work if we expand it inside an inlining?
671  --     Basically this is a cached version of 'exprIsWorkFree'
672  --
673  --  uf_guidance:  Tells us about the /size/ of the unfolding template
674
675------------------------------------------------
676data UnfoldingSource
677  = InlineRhs          -- The current rhs of the function
678                       -- Replace uf_tmpl each time around
679
680  | InlineStable       -- From an INLINE or INLINABLE pragma
681                       --   INLINE     if guidance is UnfWhen
682                       --   INLINABLE  if guidance is UnfIfGoodArgs/UnfoldNever
683                       -- (well, technically an INLINABLE might be made
684                       -- UnfWhen if it was small enough, and then
685                       -- it will behave like INLINE outside the current
686                       -- module, but that is the way automatic unfoldings
687                       -- work so it is consistent with the intended
688                       -- meaning of INLINABLE).
689                       --
690                       -- uf_tmpl may change, but only as a result of
691                       -- gentle simplification, it doesn't get updated
692                       -- to the current RHS during compilation as with
693                       -- InlineRhs.
694                       --
695                       -- See Note [InlineRules]
696
697  | InlineCompulsory   -- Something that *has* no binding, so you *must* inline it
698                       -- Only a few primop-like things have this property
699                       -- (see MkId.lhs, calls to mkCompulsoryUnfolding).
700                       -- Inline absolutely always, however boring the context.
701
702  | InlineWrapper Id   -- This unfolding is a the wrapper in a
703                       --     worker/wrapper split from the strictness analyser
704                       -- The Id is the worker-id
705                       -- Used to abbreviate the uf_tmpl in interface files
706                       --       which don't need to contain the RHS;
707                       --       it can be derived from the strictness info
708
709
710
711-- | 'UnfoldingGuidance' says when unfolding should take place
712data UnfoldingGuidance
713  = UnfWhen {   -- Inline without thinking about the *size* of the uf_tmpl
714                -- Used (a) for small *and* cheap unfoldings
715                --      (b) for INLINE functions
716                -- See Note [INLINE for small functions] in CoreUnfold
717      ug_unsat_ok  :: Bool,     -- True <=> ok to inline even if unsaturated
718      ug_boring_ok :: Bool      -- True <=> ok to inline even if the context is boring
719                -- So True,True means "always"
720    }
721
722  | UnfIfGoodArgs {     -- Arose from a normal Id; the info here is the
723                        -- result of a simple analysis of the RHS
724
725      ug_args ::  [Int],  -- Discount if the argument is evaluated.
726                          -- (i.e., a simplification will definitely
727                          -- be possible).  One elt of the list per *value* arg.
728
729      ug_size :: Int,     -- The "size" of the unfolding.
730
731      ug_res :: Int       -- Scrutinee discount: the discount to substract if the thing is in
732    }                     -- a context (case (thing args) of ...),
733                          -- (where there are the right number of arguments.)
734
735  | UnfNever        -- The RHS is big, so don't inline it
736\end{code}
737
738
739Note [DFun unfoldings]
740~~~~~~~~~~~~~~~~~~~~~~
741The Arity in a DFunUnfolding is total number of args (type and value)
742that the DFun needs to produce a dictionary.  That's not necessarily
743related to the ordinary arity of the dfun Id, esp if the class has
744one method, so the dictionary is represented by a newtype.  Example
745
746     class C a where { op :: a -> Int }
747     instance C a -> C [a] where op xs = op (head xs)
748
749The instance translates to
750
751     $dfCList :: forall a. C a => C [a]  -- Arity 2!
752     $dfCList = /\a.\d. $copList {a} d |> co
753 
754     $copList :: forall a. C a => [a] -> Int  -- Arity 2!
755     $copList = /\a.\d.\xs. op {a} d (head xs)
756
757Now we might encounter (op (dfCList {ty} d) a1 a2)
758and we want the (op (dfList {ty} d)) rule to fire, because $dfCList
759has all its arguments, even though its (value) arity is 2.  That's
760why we record the number of expected arguments in the DFunUnfolding.
761
762Note that although it's an Arity, it's most convenient for it to give
763the *total* number of arguments, both type and value.  See the use
764site in exprIsConApp_maybe.
765
766\begin{code}
767-- Constants for the UnfWhen constructor
768needSaturated, unSaturatedOk :: Bool
769needSaturated = False
770unSaturatedOk = True
771
772boringCxtNotOk, boringCxtOk :: Bool
773boringCxtOk    = True
774boringCxtNotOk = False
775
776------------------------------------------------
777noUnfolding :: Unfolding
778-- ^ There is no known 'Unfolding'
779evaldUnfolding :: Unfolding
780-- ^ This unfolding marks the associated thing as being evaluated
781
782noUnfolding    = NoUnfolding
783evaldUnfolding = OtherCon []
784
785mkOtherCon :: [AltCon] -> Unfolding
786mkOtherCon = OtherCon
787
788seqUnfolding :: Unfolding -> ()
789seqUnfolding (CoreUnfolding { uf_tmpl = e, uf_is_top = top, 
790                uf_is_value = b1, uf_is_work_free = b2, 
791                uf_expandable = b3, uf_is_conlike = b4,
792                uf_arity = a, uf_guidance = g})
793  = seqExpr e `seq` top `seq` b1 `seq` a `seq` b2 `seq` b3 `seq` b4 `seq` seqGuidance g
794
795seqUnfolding _ = ()
796
797seqGuidance :: UnfoldingGuidance -> ()
798seqGuidance (UnfIfGoodArgs ns n b) = n `seq` sum ns `seq` b `seq` ()
799seqGuidance _                      = ()
800\end{code}
801
802\begin{code}
803isStableSource :: UnfoldingSource -> Bool
804-- Keep the unfolding template
805isStableSource InlineCompulsory   = True
806isStableSource InlineStable       = True
807isStableSource (InlineWrapper {}) = True
808isStableSource InlineRhs          = False
809 
810-- | Retrieves the template of an unfolding: panics if none is known
811unfoldingTemplate :: Unfolding -> CoreExpr
812unfoldingTemplate = uf_tmpl
813
814setUnfoldingTemplate :: Unfolding -> CoreExpr -> Unfolding
815setUnfoldingTemplate unf rhs = unf { uf_tmpl = rhs }
816
817-- | Retrieves the template of an unfolding if possible
818maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
819maybeUnfoldingTemplate (CoreUnfolding { uf_tmpl = expr })       = Just expr
820maybeUnfoldingTemplate _                                        = Nothing
821
822-- | The constructors that the unfolding could never be:
823-- returns @[]@ if no information is available
824otherCons :: Unfolding -> [AltCon]
825otherCons (OtherCon cons) = cons
826otherCons _               = []
827
828-- | Determines if it is certainly the case that the unfolding will
829-- yield a value (something in HNF): returns @False@ if unsure
830isValueUnfolding :: Unfolding -> Bool
831        -- Returns False for OtherCon
832isValueUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
833isValueUnfolding _                                          = False
834
835-- | Determines if it possibly the case that the unfolding will
836-- yield a value. Unlike 'isValueUnfolding' it returns @True@
837-- for 'OtherCon'
838isEvaldUnfolding :: Unfolding -> Bool
839        -- Returns True for OtherCon
840isEvaldUnfolding (OtherCon _)                               = True
841isEvaldUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
842isEvaldUnfolding _                                          = False
843
844-- | @True@ if the unfolding is a constructor application, the application
845-- of a CONLIKE function or 'OtherCon'
846isConLikeUnfolding :: Unfolding -> Bool
847isConLikeUnfolding (OtherCon _)                             = True
848isConLikeUnfolding (CoreUnfolding { uf_is_conlike = con })  = con
849isConLikeUnfolding _                                        = False
850
851-- | Is the thing we will unfold into certainly cheap?
852isCheapUnfolding :: Unfolding -> Bool
853isCheapUnfolding (CoreUnfolding { uf_is_work_free = is_wf }) = is_wf
854isCheapUnfolding _                                           = False
855
856isExpandableUnfolding :: Unfolding -> Bool
857isExpandableUnfolding (CoreUnfolding { uf_expandable = is_expable }) = is_expable
858isExpandableUnfolding _                                              = False
859
860expandUnfolding_maybe :: Unfolding -> Maybe CoreExpr
861-- Expand an expandable unfolding; this is used in rule matching
862--   See Note [Expanding variables] in Rules.lhs
863-- The key point here is that CONLIKE things can be expanded
864expandUnfolding_maybe (CoreUnfolding { uf_expandable = True, uf_tmpl = rhs }) = Just rhs
865expandUnfolding_maybe _                                                       = Nothing
866
867isStableCoreUnfolding_maybe :: Unfolding -> Maybe UnfoldingSource
868isStableCoreUnfolding_maybe (CoreUnfolding { uf_src = src })
869   | isStableSource src   = Just src
870isStableCoreUnfolding_maybe _ = Nothing
871
872isCompulsoryUnfolding :: Unfolding -> Bool
873isCompulsoryUnfolding (CoreUnfolding { uf_src = InlineCompulsory }) = True
874isCompulsoryUnfolding _                                             = False
875
876isStableUnfolding :: Unfolding -> Bool
877-- True of unfoldings that should not be overwritten
878-- by a CoreUnfolding for the RHS of a let-binding
879isStableUnfolding (CoreUnfolding { uf_src = src }) = isStableSource src
880isStableUnfolding (DFunUnfolding {})               = True
881isStableUnfolding _                                = False
882
883unfoldingArity :: Unfolding -> Arity
884unfoldingArity (CoreUnfolding { uf_arity = arity }) = arity
885unfoldingArity _                                    = panic "unfoldingArity"
886
887isClosedUnfolding :: Unfolding -> Bool          -- No free variables
888isClosedUnfolding (CoreUnfolding {}) = False
889isClosedUnfolding (DFunUnfolding {}) = False
890isClosedUnfolding _                  = True
891
892-- | Only returns False if there is no unfolding information available at all
893hasSomeUnfolding :: Unfolding -> Bool
894hasSomeUnfolding NoUnfolding = False
895hasSomeUnfolding _           = True
896
897neverUnfoldGuidance :: UnfoldingGuidance -> Bool
898neverUnfoldGuidance UnfNever = True
899neverUnfoldGuidance _        = False
900
901canUnfold :: Unfolding -> Bool
902canUnfold (CoreUnfolding { uf_guidance = g }) = not (neverUnfoldGuidance g)
903canUnfold _                                   = False
904\end{code}
905
906Note [InlineRules]
907~~~~~~~~~~~~~~~~~
908When you say
909      {-# INLINE f #-}
910      f x = <rhs>
911you intend that calls (f e) are replaced by <rhs>[e/x] So we
912should capture (\x.<rhs>) in the Unfolding of 'f', and never meddle
913with it.  Meanwhile, we can optimise <rhs> to our heart's content,
914leaving the original unfolding intact in Unfolding of 'f'. For example
915        all xs = foldr (&&) True xs
916        any p = all . map p  {-# INLINE any #-}
917We optimise any's RHS fully, but leave the InlineRule saying "all . map p",
918which deforests well at the call site.
919
920So INLINE pragma gives rise to an InlineRule, which captures the original RHS.
921
922Moreover, it's only used when 'f' is applied to the
923specified number of arguments; that is, the number of argument on
924the LHS of the '=' sign in the original source definition.
925For example, (.) is now defined in the libraries like this
926   {-# INLINE (.) #-}
927   (.) f g = \x -> f (g x)
928so that it'll inline when applied to two arguments. If 'x' appeared
929on the left, thus
930   (.) f g x = f (g x)
931it'd only inline when applied to three arguments.  This slightly-experimental
932change was requested by Roman, but it seems to make sense.
933
934See also Note [Inlining an InlineRule] in CoreUnfold.
935
936
937Note [OccInfo in unfoldings and rules]
938~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
939In unfoldings and rules, we guarantee that the template is occ-analysed,
940so that the occurence info on the binders is correct.  This is important,
941because the Simplifier does not re-analyse the template when using it. If
942the occurrence info is wrong
943  - We may get more simpifier iterations than necessary, because
944    once-occ info isn't there
945  - More seriously, we may get an infinite loop if there's a Rec
946    without a loop breaker marked
947
948
949%************************************************************************
950%*                                                                      *
951                  AltCon
952%*                                                                      *
953%************************************************************************
954
955\begin{code}
956-- The Ord is needed for the FiniteMap used in the lookForConstructor
957-- in SimplEnv.  If you declared that lookForConstructor *ignores*
958-- constructor-applications with LitArg args, then you could get
959-- rid of this Ord.
960
961instance Outputable AltCon where
962  ppr (DataAlt dc) = ppr dc
963  ppr (LitAlt lit) = ppr lit
964  ppr DEFAULT      = ptext (sLit "__DEFAULT")
965
966instance Show AltCon where
967  showsPrec p con = showsPrecSDoc p (ppr con)
968
969cmpAlt :: (AltCon, a, b) -> (AltCon, a, b) -> Ordering
970cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
971
972ltAlt :: (AltCon, a, b) -> (AltCon, a, b) -> Bool
973ltAlt a1 a2 = (a1 `cmpAlt` a2) == LT
974
975cmpAltCon :: AltCon -> AltCon -> Ordering
976-- ^ Compares 'AltCon's within a single list of alternatives
977cmpAltCon DEFAULT      DEFAULT     = EQ
978cmpAltCon DEFAULT      _           = LT
979
980cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
981cmpAltCon (DataAlt _)  DEFAULT      = GT
982cmpAltCon (LitAlt  l1) (LitAlt  l2) = l1 `compare` l2
983cmpAltCon (LitAlt _)   DEFAULT      = GT
984
985cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+> 
986                                  ppr con1 <+> ppr con2 )
987                      LT
988\end{code}
989
990%************************************************************************
991%*                                                                      *
992\subsection{Useful synonyms}
993%*                                                                      *
994%************************************************************************
995
996Note [CoreProgram]
997~~~~~~~~~~~~~~~~~~
998The top level bindings of a program, a CoreProgram, are represented as
999a list of CoreBind
1000
1001 * Later bindings in the list can refer to earlier ones, but not vice
1002   versa.  So this is OK
1003      NonRec { x = 4 }
1004      Rec { p = ...q...x...
1005          ; q = ...p...x }
1006      Rec { f = ...p..x..f.. }
1007      NonRec { g = ..f..q...x.. }
1008   But it would NOT be ok for 'f' to refer to 'g'.
1009
1010 * The occurrence analyser does strongly-connected component analysis
1011   on each Rec binding, and splits it into a sequence of smaller
1012   bindings where possible.  So the program typically starts life as a
1013   single giant Rec, which is then dependency-analysed into smaller
1014   chunks. 
1015
1016\begin{code}
1017type CoreProgram = [CoreBind]   -- See Note [CoreProgram]
1018
1019-- | The common case for the type of binders and variables when
1020-- we are manipulating the Core language within GHC
1021type CoreBndr = Var
1022-- | Expressions where binders are 'CoreBndr's
1023type CoreExpr = Expr CoreBndr
1024-- | Argument expressions where binders are 'CoreBndr's
1025type CoreArg  = Arg  CoreBndr
1026-- | Binding groups where binders are 'CoreBndr's
1027type CoreBind = Bind CoreBndr
1028-- | Case alternatives where binders are 'CoreBndr's
1029type CoreAlt  = Alt  CoreBndr
1030\end{code}
1031
1032%************************************************************************
1033%*                                                                      *
1034\subsection{Tagging}
1035%*                                                                      *
1036%************************************************************************
1037
1038\begin{code}
1039-- | Binders are /tagged/ with a t
1040data TaggedBndr t = TB CoreBndr t       -- TB for "tagged binder"
1041
1042type TaggedBind t = Bind (TaggedBndr t)
1043type TaggedExpr t = Expr (TaggedBndr t)
1044type TaggedArg  t = Arg  (TaggedBndr t)
1045type TaggedAlt  t = Alt  (TaggedBndr t)
1046
1047instance Outputable b => Outputable (TaggedBndr b) where
1048  ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
1049
1050instance Outputable b => OutputableBndr (TaggedBndr b) where
1051  pprBndr _ b = ppr b   -- Simple
1052  pprInfixOcc  b = ppr b
1053  pprPrefixOcc b = ppr b
1054\end{code}
1055
1056
1057%************************************************************************
1058%*                                                                      *
1059\subsection{Core-constructing functions with checking}
1060%*                                                                      *
1061%************************************************************************
1062
1063\begin{code}
1064-- | Apply a list of argument expressions to a function expression in a nested fashion. Prefer to
1065-- use 'MkCore.mkCoreApps' if possible
1066mkApps    :: Expr b -> [Arg b]  -> Expr b
1067-- | Apply a list of type argument expressions to a function expression in a nested fashion
1068mkTyApps  :: Expr b -> [Type]   -> Expr b
1069-- | Apply a list of coercion argument expressions to a function expression in a nested fashion
1070mkCoApps  :: Expr b -> [Coercion] -> Expr b
1071-- | Apply a list of type or value variables to a function expression in a nested fashion
1072mkVarApps :: Expr b -> [Var] -> Expr b
1073-- | Apply a list of argument expressions to a data constructor in a nested fashion. Prefer to
1074-- use 'MkCore.mkCoreConApps' if possible
1075mkConApp      :: DataCon -> [Arg b] -> Expr b
1076
1077mkApps    f args = foldl App                       f args
1078mkTyApps  f args = foldl (\ e a -> App e (Type a)) f args
1079mkCoApps  f args = foldl (\ e a -> App e (Coercion a)) f args
1080mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
1081mkConApp con args = mkApps (Var (dataConWorkId con)) args
1082
1083
1084-- | Create a machine integer literal expression of type @Int#@ from an @Integer@.
1085-- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
1086mkIntLit      :: Integer -> Expr b
1087-- | Create a machine integer literal expression of type @Int#@ from an @Int@.
1088-- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
1089mkIntLitInt   :: Int     -> Expr b
1090
1091mkIntLit    n = Lit (mkMachInt n)
1092mkIntLitInt n = Lit (mkMachInt (toInteger n))
1093
1094-- | Create a machine word literal expression of type  @Word#@ from an @Integer@.
1095-- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
1096mkWordLit     :: Integer -> Expr b
1097-- | Create a machine word literal expression of type  @Word#@ from a @Word@.
1098-- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
1099mkWordLitWord :: Word -> Expr b
1100
1101mkWordLit     w = Lit (mkMachWord w)
1102mkWordLitWord w = Lit (mkMachWord (toInteger w))
1103
1104mkWord64LitWord64 :: Word64 -> Expr b
1105mkWord64LitWord64 w = Lit (mkMachWord64 (toInteger w))
1106
1107mkInt64LitInt64 :: Int64 -> Expr b
1108mkInt64LitInt64 w = Lit (mkMachInt64 (toInteger w))
1109
1110-- | Create a machine character literal expression of type @Char#@.
1111-- If you want an expression of type @Char@ use 'MkCore.mkCharExpr'
1112mkCharLit :: Char -> Expr b
1113-- | Create a machine string literal expression of type @Addr#@.
1114-- If you want an expression of type @String@ use 'MkCore.mkStringExpr'
1115mkStringLit :: String -> Expr b
1116
1117mkCharLit   c = Lit (mkMachChar c)
1118mkStringLit s = Lit (mkMachString s)
1119
1120-- | Create a machine single precision literal expression of type @Float#@ from a @Rational@.
1121-- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
1122mkFloatLit :: Rational -> Expr b
1123-- | Create a machine single precision literal expression of type @Float#@ from a @Float@.
1124-- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
1125mkFloatLitFloat :: Float -> Expr b
1126
1127mkFloatLit      f = Lit (mkMachFloat f)
1128mkFloatLitFloat f = Lit (mkMachFloat (toRational f))
1129
1130-- | Create a machine double precision literal expression of type @Double#@ from a @Rational@.
1131-- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
1132mkDoubleLit :: Rational -> Expr b
1133-- | Create a machine double precision literal expression of type @Double#@ from a @Double@.
1134-- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
1135mkDoubleLitDouble :: Double -> Expr b
1136
1137mkDoubleLit       d = Lit (mkMachDouble d)
1138mkDoubleLitDouble d = Lit (mkMachDouble (toRational d))
1139
1140-- | Bind all supplied binding groups over an expression in a nested let expression. Prefer to
1141-- use 'MkCore.mkCoreLets' if possible
1142mkLets        :: [Bind b] -> Expr b -> Expr b
1143-- | Bind all supplied binders over an expression in a nested lambda expression. Prefer to
1144-- use 'MkCore.mkCoreLams' if possible
1145mkLams        :: [b] -> Expr b -> Expr b
1146
1147mkLams binders body = foldr Lam body binders
1148mkLets binds body   = foldr Let body binds
1149
1150
1151-- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
1152-- this can only be used to bind something in a non-recursive @let@ expression
1153mkTyBind :: TyVar -> Type -> CoreBind
1154mkTyBind tv ty      = NonRec tv (Type ty)
1155
1156-- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
1157-- this can only be used to bind something in a non-recursive @let@ expression
1158mkCoBind :: CoVar -> Coercion -> CoreBind
1159mkCoBind cv co      = NonRec cv (Coercion co)
1160
1161-- | Convert a binder into either a 'Var' or 'Type' 'Expr' appropriately
1162varToCoreExpr :: CoreBndr -> Expr b
1163varToCoreExpr v | isTyVar v = Type (mkTyVarTy v)
1164                | isCoVar v = Coercion (mkCoVarCo v)
1165                | otherwise = ASSERT( isId v ) Var v
1166
1167varsToCoreExprs :: [CoreBndr] -> [Expr b]
1168varsToCoreExprs vs = map varToCoreExpr vs
1169\end{code}
1170
1171
1172%************************************************************************
1173%*                                                                      *
1174\subsection{Simple access functions}
1175%*                                                                      *
1176%************************************************************************
1177
1178\begin{code}
1179-- | Extract every variable by this group
1180bindersOf  :: Bind b -> [b]
1181bindersOf (NonRec binder _) = [binder]
1182bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
1183
1184-- | 'bindersOf' applied to a list of binding groups
1185bindersOfBinds :: [Bind b] -> [b]
1186bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
1187
1188rhssOfBind :: Bind b -> [Expr b]
1189rhssOfBind (NonRec _ rhs) = [rhs]
1190rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
1191
1192rhssOfAlts :: [Alt b] -> [Expr b]
1193rhssOfAlts alts = [e | (_,_,e) <- alts]
1194
1195-- | Collapse all the bindings in the supplied groups into a single
1196-- list of lhs\/rhs pairs suitable for binding in a 'Rec' binding group
1197flattenBinds :: [Bind b] -> [(b, Expr b)]
1198flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
1199flattenBinds (Rec prs1   : binds) = prs1 ++ flattenBinds binds
1200flattenBinds []                   = []
1201\end{code}
1202
1203\begin{code}
1204-- | We often want to strip off leading lambdas before getting down to
1205-- business. This function is your friend.
1206collectBinders               :: Expr b -> ([b],         Expr b)
1207-- | Collect as many type bindings as possible from the front of a nested lambda
1208collectTyBinders             :: CoreExpr -> ([TyVar],     CoreExpr)
1209-- | Collect as many value bindings as possible from the front of a nested lambda
1210collectValBinders            :: CoreExpr -> ([Id],        CoreExpr)
1211-- | Collect type binders from the front of the lambda first,
1212-- then follow up by collecting as many value bindings as possible
1213-- from the resulting stripped expression
1214collectTyAndValBinders       :: CoreExpr -> ([TyVar], [Id], CoreExpr)
1215
1216collectBinders expr
1217  = go [] expr
1218  where
1219    go bs (Lam b e) = go (b:bs) e
1220    go bs e          = (reverse bs, e)
1221
1222collectTyAndValBinders expr
1223  = (tvs, ids, body)
1224  where
1225    (tvs, body1) = collectTyBinders expr
1226    (ids, body)  = collectValBinders body1
1227
1228collectTyBinders expr
1229  = go [] expr
1230  where
1231    go tvs (Lam b e) | isTyVar b = go (b:tvs) e
1232    go tvs e                     = (reverse tvs, e)
1233
1234collectValBinders expr
1235  = go [] expr
1236  where
1237    go ids (Lam b e) | isId b = go (b:ids) e
1238    go ids body               = (reverse ids, body)
1239\end{code}
1240
1241\begin{code}
1242-- | Takes a nested application expression and returns the the function
1243-- being applied and the arguments to which it is applied
1244collectArgs :: Expr b -> (Expr b, [Arg b])
1245collectArgs expr
1246  = go expr []
1247  where
1248    go (App f a) as = go f (a:as)
1249    go e         as = (e, as)
1250\end{code}
1251
1252%************************************************************************
1253%*                                                                      *
1254\subsection{Predicates}
1255%*                                                                      *
1256%************************************************************************
1257
1258At one time we optionally carried type arguments through to runtime.
1259@isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
1260i.e. if type applications are actual lambdas because types are kept around
1261at runtime.  Similarly isRuntimeArg. 
1262
1263\begin{code}
1264-- | Will this variable exist at runtime?
1265isRuntimeVar :: Var -> Bool
1266isRuntimeVar = isId
1267
1268-- | Will this argument expression exist at runtime?
1269isRuntimeArg :: CoreExpr -> Bool
1270isRuntimeArg = isValArg
1271
1272-- | Returns @False@ iff the expression is a 'Type' or 'Coercion'
1273-- expression at its top level
1274isValArg :: Expr b -> Bool
1275isValArg e = not (isTypeArg e)
1276
1277-- | Returns @True@ iff the expression is a 'Type' or 'Coercion'
1278-- expression at its top level
1279isTyCoArg :: Expr b -> Bool
1280isTyCoArg (Type {})     = True
1281isTyCoArg (Coercion {}) = True
1282isTyCoArg _             = False
1283
1284-- | Returns @True@ iff the expression is a 'Type' expression at its
1285-- top level.  Note this does NOT include 'Coercion's.
1286isTypeArg :: Expr b -> Bool
1287isTypeArg (Type {}) = True
1288isTypeArg _         = False
1289
1290-- | The number of binders that bind values rather than types
1291valBndrCount :: [CoreBndr] -> Int
1292valBndrCount = count isId
1293
1294-- | The number of argument expressions that are values rather than types at their top level
1295valArgCount :: [Arg b] -> Int
1296valArgCount = count isValArg
1297\end{code}
1298
1299
1300%************************************************************************
1301%*                                                                      *
1302\subsection{Seq stuff}
1303%*                                                                      *
1304%************************************************************************
1305
1306\begin{code}
1307seqExpr :: CoreExpr -> ()
1308seqExpr (Var v)         = v `seq` ()
1309seqExpr (Lit lit)       = lit `seq` ()
1310seqExpr (App f a)       = seqExpr f `seq` seqExpr a
1311seqExpr (Lam b e)       = seqBndr b `seq` seqExpr e
1312seqExpr (Let b e)       = seqBind b `seq` seqExpr e
1313seqExpr (Case e b t as) = seqExpr e `seq` seqBndr b `seq` seqType t `seq` seqAlts as
1314seqExpr (Cast e co)     = seqExpr e `seq` seqCo co
1315seqExpr (Tick n e)    = seqTickish n `seq` seqExpr e
1316seqExpr (Type t)       = seqType t
1317seqExpr (Coercion co)   = seqCo co
1318
1319seqExprs :: [CoreExpr] -> ()
1320seqExprs [] = ()
1321seqExprs (e:es) = seqExpr e `seq` seqExprs es
1322
1323seqTickish :: Tickish Id -> ()
1324seqTickish ProfNote{ profNoteCC = cc } = cc `seq` ()
1325seqTickish HpcTick{} = ()
1326seqTickish Breakpoint{ breakpointFVs = ids } = seqBndrs ids
1327
1328seqBndr :: CoreBndr -> ()
1329seqBndr b = b `seq` ()
1330
1331seqBndrs :: [CoreBndr] -> ()
1332seqBndrs [] = ()
1333seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
1334
1335seqBind :: Bind CoreBndr -> ()
1336seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
1337seqBind (Rec prs)    = seqPairs prs
1338
1339seqPairs :: [(CoreBndr, CoreExpr)] -> ()
1340seqPairs [] = ()
1341seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
1342
1343seqAlts :: [CoreAlt] -> ()
1344seqAlts [] = ()
1345seqAlts ((c,bs,e):alts) = c `seq` seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
1346
1347seqRules :: [CoreRule] -> ()
1348seqRules [] = ()
1349seqRules (Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs } : rules) 
1350  = seqBndrs bndrs `seq` seqExprs (rhs:args) `seq` seqRules rules
1351seqRules (BuiltinRule {} : rules) = seqRules rules
1352\end{code}
1353
1354%************************************************************************
1355%*                                                                      *
1356\subsection{Annotated core}
1357%*                                                                      *
1358%************************************************************************
1359
1360\begin{code}
1361-- | Annotated core: allows annotation at every node in the tree
1362type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
1363
1364-- | A clone of the 'Expr' type but allowing annotation at every tree node
1365data AnnExpr' bndr annot
1366  = AnnVar      Id
1367  | AnnLit      Literal
1368  | AnnLam      bndr (AnnExpr bndr annot)
1369  | AnnApp      (AnnExpr bndr annot) (AnnExpr bndr annot)
1370  | AnnCase     (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
1371  | AnnLet      (AnnBind bndr annot) (AnnExpr bndr annot)
1372  | AnnCast     (AnnExpr bndr annot) (annot, Coercion)
1373                   -- Put an annotation on the (root of) the coercion
1374  | AnnTick     (Tickish Id) (AnnExpr bndr annot)
1375  | AnnType     Type
1376  | AnnCoercion Coercion
1377
1378-- | A clone of the 'Alt' type but allowing annotation at every tree node
1379type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
1380
1381-- | A clone of the 'Bind' type but allowing annotation at every tree node
1382data AnnBind bndr annot
1383  = AnnNonRec bndr (AnnExpr bndr annot)
1384  | AnnRec    [(bndr, AnnExpr bndr annot)]
1385\end{code}
1386
1387\begin{code}
1388-- | Takes a nested application expression and returns the the function
1389-- being applied and the arguments to which it is applied
1390collectAnnArgs :: AnnExpr b a -> (AnnExpr b a, [AnnExpr b a])
1391collectAnnArgs expr
1392  = go expr []
1393  where
1394    go (_, AnnApp f a) as = go f (a:as)
1395    go e               as = (e, as)
1396\end{code}
1397
1398\begin{code}
1399deAnnotate :: AnnExpr bndr annot -> Expr bndr
1400deAnnotate (_, e) = deAnnotate' e
1401
1402deAnnotate' :: AnnExpr' bndr annot -> Expr bndr
1403deAnnotate' (AnnType t)           = Type t
1404deAnnotate' (AnnCoercion co)      = Coercion co
1405deAnnotate' (AnnVar  v)           = Var v
1406deAnnotate' (AnnLit  lit)         = Lit lit
1407deAnnotate' (AnnLam  binder body) = Lam binder (deAnnotate body)
1408deAnnotate' (AnnApp  fun arg)     = App (deAnnotate fun) (deAnnotate arg)
1409deAnnotate' (AnnCast e (_,co))    = Cast (deAnnotate e) co
1410deAnnotate' (AnnTick tick body)   = Tick tick (deAnnotate body)
1411
1412deAnnotate' (AnnLet bind body)
1413  = Let (deAnnBind bind) (deAnnotate body)
1414  where
1415    deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
1416    deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
1417
1418deAnnotate' (AnnCase scrut v t alts)
1419  = Case (deAnnotate scrut) v t (map deAnnAlt alts)
1420
1421deAnnAlt :: AnnAlt bndr annot -> Alt bndr
1422deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
1423\end{code}
1424
1425\begin{code}
1426-- | As 'collectBinders' but for 'AnnExpr' rather than 'Expr'
1427collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
1428collectAnnBndrs e
1429  = collect [] e
1430  where
1431    collect bs (_, AnnLam b body) = collect (b:bs) body
1432    collect bs body               = (reverse bs, body)
1433\end{code}
Note: See TracBrowser for help on using the browser.