18a04455fb376099c25a8f39fd7904cb11133ee0
[ghc-hetmet.git] / compiler / coreSyn / CoreUnfold.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1994-1998
4 %
5
6 Core-syntax unfoldings
7
8 Unfoldings (which can travel across module boundaries) are in Core
9 syntax (namely @CoreExpr@s).
10
11 The type @Unfolding@ sits ``above'' simply-Core-expressions
12 unfoldings, capturing ``higher-level'' things we know about a binding,
13 usually things that the simplifier found out (e.g., ``it's a
14 literal'').  In the corner of a @CoreUnfolding@ unfolding, you will
15 find, unsurprisingly, a Core expression.
16
17 \begin{code}
18 module CoreUnfold (
19         Unfolding, UnfoldingGuidance,   -- Abstract types
20
21         noUnfolding, mkImplicitUnfolding, 
22         mkUnfolding, mkCoreUnfolding,
23         mkTopUnfolding, mkSimpleUnfolding,
24         mkInlineUnfolding, mkInlinableUnfolding, mkWwInlineRule,
25         mkCompulsoryUnfolding, mkDFunUnfolding,
26
27         interestingArg, ArgSummary(..),
28
29         couldBeSmallEnoughToInline, 
30         certainlyWillInline, smallEnoughToInline,
31
32         callSiteInline, CallCtxt(..), 
33
34         exprIsConApp_maybe
35
36     ) where
37
38 #include "HsVersions.h"
39
40 import StaticFlags
41 import DynFlags
42 import CoreSyn
43 import PprCore          ()      -- Instances
44 import TcType           ( tcSplitSigmaTy, tcSplitDFunHead )
45 import OccurAnal
46 import CoreSubst hiding( substTy )
47 import CoreFVs         ( exprFreeVars )
48 import CoreArity       ( manifestArity, exprBotStrictness_maybe )
49 import CoreUtils
50 import Id
51 import DataCon
52 import TyCon
53 import Literal
54 import PrimOp
55 import IdInfo
56 import BasicTypes       ( Arity )
57 import TcType           ( tcSplitDFunTy )
58 import Type 
59 import Coercion
60 import PrelNames
61 import VarEnv           ( mkInScopeSet )
62 import Bag
63 import Util
64 import FastTypes
65 import FastString
66 import Outputable
67 import Data.Maybe
68 \end{code}
69
70
71 %************************************************************************
72 %*                                                                      *
73 \subsection{Making unfoldings}
74 %*                                                                      *
75 %************************************************************************
76
77 \begin{code}
78 mkTopUnfolding :: Bool -> CoreExpr -> Unfolding
79 mkTopUnfolding = mkUnfolding InlineRhs True {- Top level -}
80
81 mkImplicitUnfolding :: CoreExpr -> Unfolding
82 -- For implicit Ids, do a tiny bit of optimising first
83 mkImplicitUnfolding expr = mkTopUnfolding False (simpleOptExpr expr) 
84
85 -- Note [Top-level flag on inline rules]
86 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
87 -- Slight hack: note that mk_inline_rules conservatively sets the
88 -- top-level flag to True.  It gets set more accurately by the simplifier
89 -- Simplify.simplUnfolding.
90
91 mkSimpleUnfolding :: CoreExpr -> Unfolding
92 mkSimpleUnfolding = mkUnfolding InlineRhs False False
93
94 mkDFunUnfolding :: Type -> [CoreExpr] -> Unfolding
95 mkDFunUnfolding dfun_ty ops 
96   = DFunUnfolding dfun_nargs data_con ops
97   where
98     (tvs, theta, head_ty) = tcSplitSigmaTy dfun_ty
99           -- NB: tcSplitSigmaTy: do not look through a newtype
100           --     when the dictionary type is a newtype
101     (cls, _)   = tcSplitDFunHead head_ty
102     dfun_nargs = length tvs + length theta
103     data_con   = classDataCon cls
104
105 mkWwInlineRule :: Id -> CoreExpr -> Arity -> Unfolding
106 mkWwInlineRule id expr arity
107   = mkCoreUnfolding True (InlineWrapper id) 
108                    (simpleOptExpr expr) arity
109                    (UnfWhen unSaturatedOk boringCxtNotOk)
110
111 mkCompulsoryUnfolding :: CoreExpr -> Unfolding
112 mkCompulsoryUnfolding expr         -- Used for things that absolutely must be unfolded
113   = mkCoreUnfolding True InlineCompulsory
114                     expr 0    -- Arity of unfolding doesn't matter
115                     (UnfWhen unSaturatedOk boringCxtOk)
116
117 mkInlineUnfolding :: Maybe Arity -> CoreExpr -> Unfolding
118 mkInlineUnfolding mb_arity expr 
119   = mkCoreUnfolding True         -- Note [Top-level flag on inline rules]
120                     InlineStable
121                     expr' arity 
122                     (UnfWhen unsat_ok boring_ok)
123   where
124     expr' = simpleOptExpr expr
125     (unsat_ok, arity) = case mb_arity of
126                           Nothing -> (unSaturatedOk, manifestArity expr')
127                           Just ar -> (needSaturated, ar)
128               
129     boring_ok = case calcUnfoldingGuidance True    -- Treat as cheap
130                                            False   -- But not bottoming
131                                            (arity+1) expr' of
132                   (_, UnfWhen _ boring_ok) -> boring_ok
133                   _other                   -> boringCxtNotOk
134      -- See Note [INLINE for small functions]
135
136 mkInlinableUnfolding :: CoreExpr -> Unfolding
137 mkInlinableUnfolding expr
138   = mkUnfolding InlineStable True is_bot expr
139   where
140     is_bot = isJust (exprBotStrictness_maybe expr)
141 \end{code}
142
143 Internal functions
144
145 \begin{code}
146 mkCoreUnfolding :: Bool -> UnfoldingSource -> CoreExpr
147                 -> Arity -> UnfoldingGuidance -> Unfolding
148 -- Occurrence-analyses the expression before capturing it
149 mkCoreUnfolding top_lvl src expr arity guidance 
150   = CoreUnfolding { uf_tmpl       = occurAnalyseExpr expr,
151                     uf_src        = src,
152                     uf_arity      = arity,
153                     uf_is_top     = top_lvl,
154                     uf_is_value   = exprIsHNF        expr,
155                     uf_is_conlike = exprIsConLike    expr,
156                     uf_is_cheap   = exprIsCheap      expr,
157                     uf_expandable = exprIsExpandable expr,
158                     uf_guidance   = guidance }
159
160 mkUnfolding :: UnfoldingSource -> Bool -> Bool -> CoreExpr -> Unfolding
161 -- Calculates unfolding guidance
162 -- Occurrence-analyses the expression before capturing it
163 mkUnfolding src top_lvl is_bottoming expr
164   = CoreUnfolding { uf_tmpl       = occurAnalyseExpr expr,
165                     uf_src        = src,
166                     uf_arity      = arity,
167                     uf_is_top     = top_lvl,
168                     uf_is_value   = exprIsHNF        expr,
169                     uf_is_conlike = exprIsConLike    expr,
170                     uf_expandable = exprIsExpandable expr,
171                     uf_is_cheap   = is_cheap,
172                     uf_guidance   = guidance }
173   where
174     is_cheap = exprIsCheap expr
175     (arity, guidance) = calcUnfoldingGuidance is_cheap (top_lvl && is_bottoming) 
176                                               opt_UF_CreationThreshold expr
177         -- Sometimes during simplification, there's a large let-bound thing     
178         -- which has been substituted, and so is now dead; so 'expr' contains
179         -- two copies of the thing while the occurrence-analysed expression doesn't
180         -- Nevertheless, we *don't* occ-analyse before computing the size because the
181         -- size computation bales out after a while, whereas occurrence analysis does not.
182         --
183         -- This can occasionally mean that the guidance is very pessimistic;
184         -- it gets fixed up next round.  And it should be rare, because large
185         -- let-bound things that are dead are usually caught by preInlineUnconditionally
186 \end{code}
187
188 %************************************************************************
189 %*                                                                      *
190 \subsection{The UnfoldingGuidance type}
191 %*                                                                      *
192 %************************************************************************
193
194 \begin{code}
195 calcUnfoldingGuidance
196         :: Bool         -- True <=> the rhs is cheap, or we want to treat it
197                         --          as cheap (INLINE things)     
198         -> Bool         -- True <=> this is a top-level unfolding for a
199                         --          diverging function; don't inline this
200         -> Int          -- Bomb out if size gets bigger than this
201         -> CoreExpr     -- Expression to look at
202         -> (Arity, UnfoldingGuidance)
203 calcUnfoldingGuidance expr_is_cheap top_bot bOMB_OUT_SIZE expr
204   = case collectBinders expr of { (bndrs, body) ->
205     let
206         val_bndrs   = filter isId bndrs
207         n_val_bndrs = length val_bndrs
208
209         guidance 
210           = case (sizeExpr (iUnbox bOMB_OUT_SIZE) val_bndrs body) of
211               TooBig -> UnfNever
212               SizeIs size cased_bndrs scrut_discount
213                 | uncondInline n_val_bndrs (iBox size)
214                 , expr_is_cheap
215                 -> UnfWhen unSaturatedOk boringCxtOk   -- Note [INLINE for small functions]
216                 | top_bot  -- See Note [Do not inline top-level bottoming functions]
217                 -> UnfNever
218
219                 | otherwise
220                 -> UnfIfGoodArgs { ug_args  = map (discount cased_bndrs) val_bndrs
221                                  , ug_size  = iBox size
222                                  , ug_res   = iBox scrut_discount }
223
224         discount cbs bndr
225            = foldlBag (\acc (b',n) -> if bndr==b' then acc+n else acc) 
226                       0 cbs
227     in
228     (n_val_bndrs, guidance) }
229 \end{code}
230
231 Note [Computing the size of an expression]
232 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
233 The basic idea of sizeExpr is obvious enough: count nodes.  But getting the
234 heuristics right has taken a long time.  Here's the basic strategy:
235
236     * Variables, literals: 0
237       (Exception for string literals, see litSize.)
238
239     * Function applications (f e1 .. en): 1 + #value args
240
241     * Constructor applications: 1, regardless of #args
242
243     * Let(rec): 1 + size of components
244
245     * Note, cast: 0
246
247 Examples
248
249   Size  Term
250   --------------
251     0     42#
252     0     x
253     0     True
254     2     f x
255     1     Just x
256     4     f (g x)
257
258 Notice that 'x' counts 0, while (f x) counts 2.  That's deliberate: there's
259 a function call to account for.  Notice also that constructor applications 
260 are very cheap, because exposing them to a caller is so valuable.
261
262
263 Note [Do not inline top-level bottoming functions]
264 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
265 The FloatOut pass has gone to some trouble to float out calls to 'error' 
266 and similar friends.  See Note [Bottoming floats] in SetLevels.
267 Do not re-inline them!  But we *do* still inline if they are very small
268 (the uncondInline stuff).
269
270
271 Note [INLINE for small functions]
272 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
273 Consider        {-# INLINE f #-}
274                 f x = Just x
275                 g y = f y
276 Then f's RHS is no larger than its LHS, so we should inline it into
277 even the most boring context.  In general, f the function is
278 sufficiently small that its body is as small as the call itself, the
279 inline unconditionally, regardless of how boring the context is.
280
281 Things to note:
282
283  * We inline *unconditionally* if inlined thing is smaller (using sizeExpr)
284    than the thing it's replacing.  Notice that
285       (f x) --> (g 3)             -- YES, unconditionally
286       (f x) --> x : []            -- YES, *even though* there are two
287                                   --      arguments to the cons
288       x     --> g 3               -- NO
289       x     --> Just v            -- NO
290
291   It's very important not to unconditionally replace a variable by
292   a non-atomic term.
293
294 * We do this even if the thing isn't saturated, else we end up with the
295   silly situation that
296      f x y = x
297      ...map (f 3)...
298   doesn't inline.  Even in a boring context, inlining without being
299   saturated will give a lambda instead of a PAP, and will be more
300   efficient at runtime.
301
302 * However, when the function's arity > 0, we do insist that it 
303   has at least one value argument at the call site.  Otherwise we find this:
304        f = /\a \x:a. x
305        d = /\b. MkD (f b)
306   If we inline f here we get
307        d = /\b. MkD (\x:b. x)
308   and then prepareRhs floats out the argument, abstracting the type
309   variables, so we end up with the original again!
310
311
312 \begin{code}
313 uncondInline :: Arity -> Int -> Bool
314 -- Inline unconditionally if there no size increase
315 -- Size of call is arity (+1 for the function)
316 -- See Note [INLINE for small functions]
317 uncondInline arity size 
318   | arity == 0 = size == 0
319   | otherwise  = size <= arity + 1
320 \end{code}
321
322
323 \begin{code}
324 sizeExpr :: FastInt         -- Bomb out if it gets bigger than this
325          -> [Id]            -- Arguments; we're interested in which of these
326                             -- get case'd
327          -> CoreExpr
328          -> ExprSize
329
330 -- Note [Computing the size of an expression]
331
332 sizeExpr bOMB_OUT_SIZE top_args expr
333   = size_up expr
334   where
335     size_up (Cast e _) = size_up e
336     size_up (Note _ e) = size_up e
337     size_up (Type _)   = sizeZero           -- Types cost nothing
338     size_up (Lit lit)  = sizeN (litSize lit)
339     size_up (Var f)    = size_up_call f []  -- Make sure we get constructor
340                                             -- discounts even on nullary constructors
341
342     size_up (App fun (Type _)) = size_up fun
343     size_up (App fun arg)      = size_up arg  `addSizeNSD`
344                                  size_up_app fun [arg]
345
346     size_up (Lam b e) | isId b    = lamScrutDiscount (size_up e `addSizeN` 1)
347                       | otherwise = size_up e
348
349     size_up (Let (NonRec binder rhs) body)
350       = size_up rhs             `addSizeNSD`
351         size_up body            `addSizeN`
352         (if isUnLiftedType (idType binder) then 0 else 1)
353                 -- For the allocation
354                 -- If the binder has an unlifted type there is no allocation
355
356     size_up (Let (Rec pairs) body)
357       = foldr (addSizeNSD . size_up . snd) 
358               (size_up body `addSizeN` length pairs)    -- (length pairs) for the allocation
359               pairs
360
361     size_up (Case (Var v) _ _ alts) 
362         | v `elem` top_args             -- We are scrutinising an argument variable
363         = alts_size (foldr1 addAltSize alt_sizes)
364                     (foldr1 maxSize alt_sizes)
365                 -- Good to inline if an arg is scrutinised, because
366                 -- that may eliminate allocation in the caller
367                 -- And it eliminates the case itself
368         where
369           alt_sizes = map size_up_alt alts
370
371                 -- alts_size tries to compute a good discount for
372                 -- the case when we are scrutinising an argument variable
373           alts_size (SizeIs tot tot_disc tot_scrut)  -- Size of all alternatives
374                     (SizeIs max _        _)          -- Size of biggest alternative
375                 = SizeIs tot (unitBag (v, iBox (_ILIT(2) +# tot -# max)) `unionBags` tot_disc) tot_scrut
376                         -- If the variable is known, we produce a discount that
377                         -- will take us back to 'max', the size of the largest alternative
378                         -- The 1+ is a little discount for reduced allocation in the caller
379                         --
380                         -- Notice though, that we return tot_disc, the total discount from 
381                         -- all branches.  I think that's right.
382
383           alts_size tot_size _ = tot_size
384
385     size_up (Case e _ _ alts) = size_up e  `addSizeNSD` 
386                                 foldr (addAltSize . size_up_alt) sizeZero alts
387                 -- We don't charge for the case itself
388                 -- It's a strict thing, and the price of the call
389                 -- is paid by scrut.  Also consider
390                 --      case f x of DEFAULT -> e
391                 -- This is just ';'!  Don't charge for it.
392                 --
393                 -- Moreover, we charge one per alternative.
394
395     ------------ 
396     -- size_up_app is used when there's ONE OR MORE value args
397     size_up_app (App fun arg) args 
398         | isTypeArg arg            = size_up_app fun args
399         | otherwise                = size_up arg  `addSizeNSD`
400                                      size_up_app fun (arg:args)
401     size_up_app (Var fun)     args = size_up_call fun args
402     size_up_app other         args = size_up other `addSizeN` length args
403
404     ------------ 
405     size_up_call :: Id -> [CoreExpr] -> ExprSize
406     size_up_call fun val_args
407        = case idDetails fun of
408            FCallId _        -> sizeN opt_UF_DearOp
409            DataConWorkId dc -> conSize    dc (length val_args)
410            PrimOpId op      -> primOpSize op (length val_args)
411            ClassOpId _      -> classOpSize top_args val_args
412            _                -> funSize top_args fun (length val_args)
413
414     ------------ 
415     size_up_alt (_con, _bndrs, rhs) = size_up rhs `addSizeN` 1
416         -- Don't charge for args, so that wrappers look cheap
417         -- (See comments about wrappers with Case)
418         --
419         -- IMPORATANT: *do* charge 1 for the alternative, else we 
420         -- find that giant case nests are treated as practically free
421         -- A good example is Foreign.C.Error.errrnoToIOError
422
423     ------------
424         -- These addSize things have to be here because
425         -- I don't want to give them bOMB_OUT_SIZE as an argument
426     addSizeN TooBig          _  = TooBig
427     addSizeN (SizeIs n xs d) m  = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
428     
429         -- addAltSize is used to add the sizes of case alternatives
430     addAltSize TooBig            _      = TooBig
431     addAltSize _                 TooBig = TooBig
432     addAltSize (SizeIs n1 xs d1) (SizeIs n2 ys d2) 
433         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) 
434                                  (xs `unionBags` ys) 
435                                  (d1 +# d2)   -- Note [addAltSize result discounts]
436
437         -- This variant ignores the result discount from its LEFT argument
438         -- It's used when the second argument isn't part of the result
439     addSizeNSD TooBig            _      = TooBig
440     addSizeNSD _                 TooBig = TooBig
441     addSizeNSD (SizeIs n1 xs _) (SizeIs n2 ys d2) 
442         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) 
443                                  (xs `unionBags` ys) 
444                                  d2  -- Ignore d1
445 \end{code}
446
447 \begin{code}
448 -- | Finds a nominal size of a string literal.
449 litSize :: Literal -> Int
450 -- Used by CoreUnfold.sizeExpr
451 litSize (MachStr str) = 1 + ((lengthFS str + 3) `div` 4)
452         -- If size could be 0 then @f "x"@ might be too small
453         -- [Sept03: make literal strings a bit bigger to avoid fruitless 
454         --  duplication of little strings]
455 litSize _other = 0    -- Must match size of nullary constructors
456                       -- Key point: if  x |-> 4, then x must inline unconditionally
457                       --            (eg via case binding)
458
459 classOpSize :: [Id] -> [CoreExpr] -> ExprSize
460 -- See Note [Conlike is interesting]
461 classOpSize _ [] 
462   = sizeZero
463 classOpSize top_args (arg1 : other_args)
464   = SizeIs (iUnbox size) arg_discount (_ILIT(0))
465   where
466     size = 2 + length other_args
467     -- If the class op is scrutinising a lambda bound dictionary then
468     -- give it a discount, to encourage the inlining of this function
469     -- The actual discount is rather arbitrarily chosen
470     arg_discount = case arg1 of
471                      Var dict | dict `elem` top_args 
472                               -> unitBag (dict, opt_UF_DictDiscount)
473                      _other   -> emptyBag
474                      
475 funSize :: [Id] -> Id -> Int -> ExprSize
476 -- Size for functions that are not constructors or primops
477 -- Note [Function applications]
478 funSize top_args fun n_val_args
479   | fun `hasKey` buildIdKey   = buildSize
480   | fun `hasKey` augmentIdKey = augmentSize
481   | otherwise = SizeIs (iUnbox size) arg_discount (iUnbox res_discount)
482   where
483     some_val_args = n_val_args > 0
484
485     arg_discount | some_val_args && fun `elem` top_args
486                  = unitBag (fun, opt_UF_FunAppDiscount)
487                  | otherwise = emptyBag
488         -- If the function is an argument and is applied
489         -- to some values, give it an arg-discount
490
491     res_discount | idArity fun > n_val_args = opt_UF_FunAppDiscount
492                  | otherwise                = 0
493         -- If the function is partially applied, show a result discount
494
495     size | some_val_args = 1 + n_val_args
496          | otherwise     = 0
497         -- The 1+ is for the function itself
498         -- Add 1 for each non-trivial arg;
499         -- the allocation cost, as in let(rec)
500   
501
502 conSize :: DataCon -> Int -> ExprSize
503 conSize dc n_val_args
504   | n_val_args == 0 = SizeIs (_ILIT(0)) emptyBag (_ILIT(1))     -- Like variables
505
506 -- See Note [Constructor size]
507   | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (iUnbox n_val_args +# _ILIT(1))
508
509 -- See Note [Unboxed tuple result discount]
510 --  | isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (_ILIT(0))
511
512 -- See Note [Constructor size]
513   | otherwise = SizeIs (_ILIT(1)) emptyBag (iUnbox n_val_args +# _ILIT(1))
514 \end{code}
515
516 Note [Constructor size]
517 ~~~~~~~~~~~~~~~~~~~~~~~
518 Treat a constructors application as size 1, regardless of how many
519 arguments it has; we are keen to expose them (and we charge separately
520 for their args).  We can't treat them as size zero, else we find that
521 (Just x) has size 0, which is the same as a lone variable; and hence
522 'v' will always be replaced by (Just x), where v is bound to Just x.
523
524 However, unboxed tuples count as size zero. I found occasions where we had 
525         f x y z = case op# x y z of { s -> (# s, () #) }
526 and f wasn't getting inlined.
527
528 Note [Unboxed tuple result discount]
529 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
530 I tried giving unboxed tuples a *result discount* of zero (see the
531 commented-out line).  Why?  When returned as a result they do not
532 allocate, so maybe we don't want to charge so much for them If you
533 have a non-zero discount here, we find that workers often get inlined
534 back into wrappers, because it look like
535     f x = case $wf x of (# a,b #) -> (a,b)
536 and we are keener because of the case.  However while this change
537 shrank binary sizes by 0.5% it also made spectral/boyer allocate 5%
538 more. All other changes were very small. So it's not a big deal but I
539 didn't adopt the idea.
540
541 \begin{code}
542 primOpSize :: PrimOp -> Int -> ExprSize
543 primOpSize op n_val_args
544  | not (primOpIsDupable op) = sizeN opt_UF_DearOp
545  | not (primOpOutOfLine op) = sizeN 1
546         -- Be very keen to inline simple primops.
547         -- We give a discount of 1 for each arg so that (op# x y z) costs 2.
548         -- We can't make it cost 1, else we'll inline let v = (op# x y z) 
549         -- at every use of v, which is excessive.
550         --
551         -- A good example is:
552         --      let x = +# p q in C {x}
553         -- Even though x get's an occurrence of 'many', its RHS looks cheap,
554         -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
555
556  | otherwise = sizeN n_val_args
557
558
559 buildSize :: ExprSize
560 buildSize = SizeIs (_ILIT(0)) emptyBag (_ILIT(4))
561         -- We really want to inline applications of build
562         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
563         -- Indeed, we should add a result_discount becuause build is 
564         -- very like a constructor.  We don't bother to check that the
565         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
566         -- The "4" is rather arbitrary.
567
568 augmentSize :: ExprSize
569 augmentSize = SizeIs (_ILIT(0)) emptyBag (_ILIT(4))
570         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
571         -- e plus ys. The -2 accounts for the \cn 
572
573 -- When we return a lambda, give a discount if it's used (applied)
574 lamScrutDiscount :: ExprSize -> ExprSize
575 lamScrutDiscount (SizeIs n vs _) = SizeIs n vs (iUnbox opt_UF_FunAppDiscount)
576 lamScrutDiscount TooBig          = TooBig
577 \end{code}
578
579 Note [addAltSize result discounts]
580 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
581 When adding the size of alternatives, we *add* the result discounts
582 too, rather than take the *maximum*.  For a multi-branch case, this
583 gives a discount for each branch that returns a constructor, making us
584 keener to inline.  I did try using 'max' instead, but it makes nofib 
585 'rewrite' and 'puzzle' allocate significantly more, and didn't make
586 binary sizes shrink significantly either.
587
588 Note [Discounts and thresholds]
589 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
590 Constants for discounts and thesholds are defined in main/StaticFlags,
591 all of form opt_UF_xxxx.   They are:
592
593 opt_UF_CreationThreshold (45)
594      At a definition site, if the unfolding is bigger than this, we
595      may discard it altogether
596
597 opt_UF_UseThreshold (6)
598      At a call site, if the unfolding, less discounts, is smaller than
599      this, then it's small enough inline
600
601 opt_UF_KeennessFactor (1.5)
602      Factor by which the discounts are multiplied before 
603      subtracting from size
604
605 opt_UF_DictDiscount (1)
606      The discount for each occurrence of a dictionary argument
607      as an argument of a class method.  Should be pretty small
608      else big functions may get inlined
609
610 opt_UF_FunAppDiscount (6)
611      Discount for a function argument that is applied.  Quite
612      large, because if we inline we avoid the higher-order call.
613
614 opt_UF_DearOp (4)
615      The size of a foreign call or not-dupable PrimOp
616
617
618 Note [Function applications]
619 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
620 In a function application (f a b)
621
622   - If 'f' is an argument to the function being analysed, 
623     and there's at least one value arg, record a FunAppDiscount for f
624
625   - If the application if a PAP (arity > 2 in this example)
626     record a *result* discount (because inlining
627     with "extra" args in the call may mean that we now 
628     get a saturated application)
629
630 Code for manipulating sizes
631
632 \begin{code}
633 data ExprSize = TooBig
634               | SizeIs FastInt          -- Size found
635                        (Bag (Id,Int))   -- Arguments cased herein, and discount for each such
636                        FastInt          -- Size to subtract if result is scrutinised 
637                                         -- by a case expression
638
639 instance Outputable ExprSize where
640   ppr TooBig         = ptext (sLit "TooBig")
641   ppr (SizeIs a _ c) = brackets (int (iBox a) <+> int (iBox c))
642
643 -- subtract the discount before deciding whether to bale out. eg. we
644 -- want to inline a large constructor application into a selector:
645 --      tup = (a_1, ..., a_99)
646 --      x = case tup of ...
647 --
648 mkSizeIs :: FastInt -> FastInt -> Bag (Id, Int) -> FastInt -> ExprSize
649 mkSizeIs max n xs d | (n -# d) ># max = TooBig
650                     | otherwise       = SizeIs n xs d
651  
652 maxSize :: ExprSize -> ExprSize -> ExprSize
653 maxSize TooBig         _                                  = TooBig
654 maxSize _              TooBig                             = TooBig
655 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2  = s1
656                                               | otherwise = s2
657
658 sizeZero :: ExprSize
659 sizeN :: Int -> ExprSize
660
661 sizeZero = SizeIs (_ILIT(0))  emptyBag (_ILIT(0))
662 sizeN n  = SizeIs (iUnbox n) emptyBag (_ILIT(0))
663 \end{code}
664
665
666 %************************************************************************
667 %*                                                                      *
668 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
669 %*                                                                      *
670 %************************************************************************
671
672 We use 'couldBeSmallEnoughToInline' to avoid exporting inlinings that
673 we ``couldn't possibly use'' on the other side.  Can be overridden w/
674 flaggery.  Just the same as smallEnoughToInline, except that it has no
675 actual arguments.
676
677 \begin{code}
678 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
679 couldBeSmallEnoughToInline threshold rhs 
680   = case sizeExpr (iUnbox threshold) [] body of
681        TooBig -> False
682        _      -> True
683   where
684     (_, body) = collectBinders rhs
685
686 ----------------
687 smallEnoughToInline :: Unfolding -> Bool
688 smallEnoughToInline (CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_size = size}})
689   = size <= opt_UF_UseThreshold
690 smallEnoughToInline _
691   = False
692
693 ----------------
694 certainlyWillInline :: Unfolding -> Bool
695   -- Sees if the unfolding is pretty certain to inline  
696 certainlyWillInline (CoreUnfolding { uf_is_cheap = is_cheap, uf_arity = n_vals, uf_guidance = guidance })
697   = case guidance of
698       UnfNever      -> False
699       UnfWhen {}    -> True
700       UnfIfGoodArgs { ug_size = size} 
701                     -> is_cheap && size - (n_vals +1) <= opt_UF_UseThreshold
702
703 certainlyWillInline _
704   = False
705 \end{code}
706
707 %************************************************************************
708 %*                                                                      *
709 \subsection{callSiteInline}
710 %*                                                                      *
711 %************************************************************************
712
713 This is the key function.  It decides whether to inline a variable at a call site
714
715 callSiteInline is used at call sites, so it is a bit more generous.
716 It's a very important function that embodies lots of heuristics.
717 A non-WHNF can be inlined if it doesn't occur inside a lambda,
718 and occurs exactly once or 
719     occurs once in each branch of a case and is small
720
721 If the thing is in WHNF, there's no danger of duplicating work, 
722 so we can inline if it occurs once, or is small
723
724 NOTE: we don't want to inline top-level functions that always diverge.
725 It just makes the code bigger.  Tt turns out that the convenient way to prevent
726 them inlining is to give them a NOINLINE pragma, which we do in 
727 StrictAnal.addStrictnessInfoToTopId
728
729 \begin{code}
730 callSiteInline :: DynFlags
731                -> Id                    -- The Id
732                -> Unfolding             -- Its unfolding (if active)
733                -> Bool                  -- True if there are are no arguments at all (incl type args)
734                -> [ArgSummary]          -- One for each value arg; True if it is interesting
735                -> CallCtxt              -- True <=> continuation is interesting
736                -> Maybe CoreExpr        -- Unfolding, if any
737
738
739 instance Outputable ArgSummary where
740   ppr TrivArg    = ptext (sLit "TrivArg")
741   ppr NonTrivArg = ptext (sLit "NonTrivArg")
742   ppr ValueArg   = ptext (sLit "ValueArg")
743
744 data CallCtxt = BoringCtxt
745
746               | ArgCtxt         -- We are somewhere in the argument of a function
747                         Bool    -- True  <=> we're somewhere in the RHS of function with rules
748                                 -- False <=> we *are* the argument of a function with non-zero
749                                 --           arg discount
750                                 --        OR 
751                                 --           we *are* the RHS of a let  Note [RHS of lets]
752                                 -- In both cases, be a little keener to inline
753
754               | ValAppCtxt      -- We're applied to at least one value arg
755                                 -- This arises when we have ((f x |> co) y)
756                                 -- Then the (f x) has argument 'x' but in a ValAppCtxt
757
758               | CaseCtxt        -- We're the scrutinee of a case
759                                 -- that decomposes its scrutinee
760
761 instance Outputable CallCtxt where
762   ppr BoringCtxt      = ptext (sLit "BoringCtxt")
763   ppr (ArgCtxt rules) = ptext (sLit "ArgCtxt") <+> ppr rules
764   ppr CaseCtxt        = ptext (sLit "CaseCtxt")
765   ppr ValAppCtxt      = ptext (sLit "ValAppCtxt")
766
767 callSiteInline dflags id unfolding lone_variable arg_infos cont_info
768   = case unfolding of {
769         NoUnfolding      -> Nothing ;
770         OtherCon _       -> Nothing ;
771         DFunUnfolding {} -> Nothing ;   -- Never unfold a DFun
772         CoreUnfolding { uf_tmpl = unf_template, uf_is_top = is_top, 
773                         uf_is_cheap = is_cheap, uf_arity = uf_arity, uf_guidance = guidance } ->
774                         -- uf_arity will typically be equal to (idArity id), 
775                         -- but may be less for InlineRules
776     let
777         n_val_args = length arg_infos
778         saturated  = n_val_args >= uf_arity
779
780         result | yes_or_no = Just unf_template
781                | otherwise = Nothing
782
783         interesting_args = any nonTriv arg_infos 
784                 -- NB: (any nonTriv arg_infos) looks at the
785                 -- over-saturated args too which is "wrong"; 
786                 -- but if over-saturated we inline anyway.
787
788                -- some_benefit is used when the RHS is small enough
789                -- and the call has enough (or too many) value
790                -- arguments (ie n_val_args >= arity). But there must
791                -- be *something* interesting about some argument, or the
792                -- result context, to make it worth inlining
793         some_benefit 
794            | not saturated = interesting_args   -- Under-saturated
795                                                 -- Note [Unsaturated applications]
796            | n_val_args > uf_arity = True       -- Over-saturated
797            | otherwise = interesting_args       -- Saturated
798                       || interesting_saturated_call 
799
800         interesting_saturated_call 
801           = case cont_info of
802               BoringCtxt -> not is_top && uf_arity > 0        -- Note [Nested functions]
803               CaseCtxt   -> not (lone_variable && is_cheap)   -- Note [Lone variables]
804               ArgCtxt {} -> uf_arity > 0                      -- Note [Inlining in ArgCtxt]
805               ValAppCtxt -> True                              -- Note [Cast then apply]
806
807         (yes_or_no, extra_doc)
808           = case guidance of
809               UnfNever -> (False, empty)
810
811               UnfWhen unsat_ok boring_ok 
812                  -> (enough_args && (boring_ok || some_benefit), empty )
813                  where      -- See Note [INLINE for small functions]
814                    enough_args = saturated || (unsat_ok && n_val_args > 0)
815
816               UnfIfGoodArgs { ug_args = arg_discounts, ug_res = res_discount, ug_size = size }
817                  -> ( is_cheap && some_benefit && small_enough
818                     , (text "discounted size =" <+> int discounted_size) )
819                  where
820                    discounted_size = size - discount
821                    small_enough = discounted_size <= opt_UF_UseThreshold
822                    discount = computeDiscount uf_arity arg_discounts 
823                                               res_discount arg_infos cont_info
824                 
825     in    
826     if (dopt Opt_D_dump_inlinings dflags && dopt Opt_D_verbose_core2core dflags) then
827         pprTrace ("Considering inlining: " ++ showSDoc (ppr id))
828                  (vcat [text "arg infos" <+> ppr arg_infos,
829                         text "uf arity" <+> ppr uf_arity,
830                         text "interesting continuation" <+> ppr cont_info,
831                         text "some_benefit" <+> ppr some_benefit,
832                         text "is cheap:" <+> ppr is_cheap,
833                         text "guidance" <+> ppr guidance,
834                         extra_doc,
835                         text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"])
836                   result
837     else
838     result
839     }
840 \end{code}
841
842 Note [RHS of lets]
843 ~~~~~~~~~~~~~~~~~~
844 Be a tiny bit keener to inline in the RHS of a let, because that might
845 lead to good thing later
846      f y = (y,y,y)
847      g y = let x = f y in ...(case x of (a,b,c) -> ...) ...
848 We'd inline 'f' if the call was in a case context, and it kind-of-is,
849 only we can't see it.  So we treat the RHS of a let as not-totally-boring.
850     
851 Note [Unsaturated applications]
852 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
853 When a call is not saturated, we *still* inline if one of the
854 arguments has interesting structure.  That's sometimes very important.
855 A good example is the Ord instance for Bool in Base:
856
857  Rec {
858     $fOrdBool =GHC.Classes.D:Ord
859                  @ Bool
860                  ...
861                  $cmin_ajX
862
863     $cmin_ajX [Occ=LoopBreaker] :: Bool -> Bool -> Bool
864     $cmin_ajX = GHC.Classes.$dmmin @ Bool $fOrdBool
865   }
866
867 But the defn of GHC.Classes.$dmmin is:
868
869   $dmmin :: forall a. GHC.Classes.Ord a => a -> a -> a
870     {- Arity: 3, HasNoCafRefs, Strictness: SLL,
871        Unfolding: (\ @ a $dOrd :: GHC.Classes.Ord a x :: a y :: a ->
872                    case @ a GHC.Classes.<= @ a $dOrd x y of wild {
873                      GHC.Bool.False -> y GHC.Bool.True -> x }) -}
874
875 We *really* want to inline $dmmin, even though it has arity 3, in
876 order to unravel the recursion.
877
878
879 Note [Things to watch]
880 ~~~~~~~~~~~~~~~~~~~~~~
881 *   { y = I# 3; x = y `cast` co; ...case (x `cast` co) of ... }
882     Assume x is exported, so not inlined unconditionally.
883     Then we want x to inline unconditionally; no reason for it 
884     not to, and doing so avoids an indirection.
885
886 *   { x = I# 3; ....f x.... }
887     Make sure that x does not inline unconditionally!  
888     Lest we get extra allocation.
889
890 Note [Inlining an InlineRule]
891 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
892 An InlineRules is used for
893   (a) programmer INLINE pragmas
894   (b) inlinings from worker/wrapper
895
896 For (a) the RHS may be large, and our contract is that we *only* inline
897 when the function is applied to all the arguments on the LHS of the
898 source-code defn.  (The uf_arity in the rule.)
899
900 However for worker/wrapper it may be worth inlining even if the 
901 arity is not satisfied (as we do in the CoreUnfolding case) so we don't
902 require saturation.
903
904
905 Note [Nested functions]
906 ~~~~~~~~~~~~~~~~~~~~~~~
907 If a function has a nested defn we also record some-benefit, on the
908 grounds that we are often able to eliminate the binding, and hence the
909 allocation, for the function altogether; this is good for join points.
910 But this only makes sense for *functions*; inlining a constructor
911 doesn't help allocation unless the result is scrutinised.  UNLESS the
912 constructor occurs just once, albeit possibly in multiple case
913 branches.  Then inlining it doesn't increase allocation, but it does
914 increase the chance that the constructor won't be allocated at all in
915 the branches that don't use it.
916
917 Note [Cast then apply]
918 ~~~~~~~~~~~~~~~~~~~~~~
919 Consider
920    myIndex = __inline_me ( (/\a. <blah>) |> co )
921    co :: (forall a. a -> a) ~ (forall a. T a)
922      ... /\a.\x. case ((myIndex a) |> sym co) x of { ... } ...
923
924 We need to inline myIndex to unravel this; but the actual call (myIndex a) has
925 no value arguments.  The ValAppCtxt gives it enough incentive to inline.
926
927 Note [Inlining in ArgCtxt]
928 ~~~~~~~~~~~~~~~~~~~~~~~~~~
929 The condition (arity > 0) here is very important, because otherwise
930 we end up inlining top-level stuff into useless places; eg
931    x = I# 3#
932    f = \y.  g x
933 This can make a very big difference: it adds 16% to nofib 'integer' allocs,
934 and 20% to 'power'.
935
936 At one stage I replaced this condition by 'True' (leading to the above 
937 slow-down).  The motivation was test eyeball/inline1.hs; but that seems
938 to work ok now.
939
940 NOTE: arguably, we should inline in ArgCtxt only if the result of the
941 call is at least CONLIKE.  At least for the cases where we use ArgCtxt
942 for the RHS of a 'let', we only profit from the inlining if we get a 
943 CONLIKE thing (modulo lets).
944
945 Note [Lone variables]   See also Note [Interaction of exprIsCheap and lone variables]
946 ~~~~~~~~~~~~~~~~~~~~~   which appears below
947 The "lone-variable" case is important.  I spent ages messing about
948 with unsatisfactory varaints, but this is nice.  The idea is that if a
949 variable appears all alone
950
951         as an arg of lazy fn, or rhs    BoringCtxt
952         as scrutinee of a case          CaseCtxt
953         as arg of a fn                  ArgCtxt
954 AND
955         it is bound to a cheap expression
956
957 then we should not inline it (unless there is some other reason,
958 e.g. is is the sole occurrence).  That is what is happening at 
959 the use of 'lone_variable' in 'interesting_saturated_call'.
960
961 Why?  At least in the case-scrutinee situation, turning
962         let x = (a,b) in case x of y -> ...
963 into
964         let x = (a,b) in case (a,b) of y -> ...
965 and thence to 
966         let x = (a,b) in let y = (a,b) in ...
967 is bad if the binding for x will remain.
968
969 Another example: I discovered that strings
970 were getting inlined straight back into applications of 'error'
971 because the latter is strict.
972         s = "foo"
973         f = \x -> ...(error s)...
974
975 Fundamentally such contexts should not encourage inlining because the
976 context can ``see'' the unfolding of the variable (e.g. case or a
977 RULE) so there's no gain.  If the thing is bound to a value.
978
979 However, watch out:
980
981  * Consider this:
982         foo = _inline_ (\n. [n])
983         bar = _inline_ (foo 20)
984         baz = \n. case bar of { (m:_) -> m + n }
985    Here we really want to inline 'bar' so that we can inline 'foo'
986    and the whole thing unravels as it should obviously do.  This is 
987    important: in the NDP project, 'bar' generates a closure data
988    structure rather than a list. 
989
990    So the non-inlining of lone_variables should only apply if the
991    unfolding is regarded as cheap; because that is when exprIsConApp_maybe
992    looks through the unfolding.  Hence the "&& is_cheap" in the
993    InlineRule branch.
994
995  * Even a type application or coercion isn't a lone variable.
996    Consider
997         case $fMonadST @ RealWorld of { :DMonad a b c -> c }
998    We had better inline that sucker!  The case won't see through it.
999
1000    For now, I'm treating treating a variable applied to types 
1001    in a *lazy* context "lone". The motivating example was
1002         f = /\a. \x. BIG
1003         g = /\a. \y.  h (f a)
1004    There's no advantage in inlining f here, and perhaps
1005    a significant disadvantage.  Hence some_val_args in the Stop case
1006
1007 Note [Interaction of exprIsCheap and lone variables]
1008 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1009 The lone-variable test says "don't inline if a case expression
1010 scrutines a lone variable whose unfolding is cheap".  It's very 
1011 important that, under these circumstances, exprIsConApp_maybe
1012 can spot a constructor application. So, for example, we don't
1013 consider
1014         let x = e in (x,x)
1015 to be cheap, and that's good because exprIsConApp_maybe doesn't
1016 think that expression is a constructor application.
1017
1018 I used to test is_value rather than is_cheap, which was utterly
1019 wrong, because the above expression responds True to exprIsHNF.
1020
1021 This kind of thing can occur if you have
1022
1023         {-# INLINE foo #-}
1024         foo = let x = e in (x,x)
1025
1026 which Roman did.
1027
1028 \begin{code}
1029 computeDiscount :: Int -> [Int] -> Int -> [ArgSummary] -> CallCtxt -> Int
1030 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos cont_info
1031         -- We multiple the raw discounts (args_discount and result_discount)
1032         -- ty opt_UnfoldingKeenessFactor because the former have to do with
1033         --  *size* whereas the discounts imply that there's some extra 
1034         --  *efficiency* to be gained (e.g. beta reductions, case reductions) 
1035         -- by inlining.
1036
1037   = 1           -- Discount of 1 because the result replaces the call
1038                 -- so we count 1 for the function itself
1039
1040     + length (take n_vals_wanted arg_infos)
1041                -- Discount of (un-scaled) 1 for each arg supplied, 
1042                -- because the result replaces the call
1043
1044     + round (opt_UF_KeenessFactor * 
1045              fromIntegral (arg_discount + res_discount'))
1046   where
1047     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
1048
1049     mk_arg_discount _        TrivArg    = 0 
1050     mk_arg_discount _        NonTrivArg = 1   
1051     mk_arg_discount discount ValueArg   = discount 
1052
1053     res_discount' = case cont_info of
1054                         BoringCtxt  -> 0
1055                         CaseCtxt    -> res_discount
1056                         _other      -> 4 `min` res_discount
1057                 -- res_discount can be very large when a function returns
1058                 -- constructors; but we only want to invoke that large discount
1059                 -- when there's a case continuation.
1060                 -- Otherwise we, rather arbitrarily, threshold it.  Yuk.
1061                 -- But we want to aovid inlining large functions that return 
1062                 -- constructors into contexts that are simply "interesting"
1063 \end{code}
1064
1065 %************************************************************************
1066 %*                                                                      *
1067         Interesting arguments
1068 %*                                                                      *
1069 %************************************************************************
1070
1071 Note [Interesting arguments]
1072 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1073 An argument is interesting if it deserves a discount for unfoldings
1074 with a discount in that argument position.  The idea is to avoid
1075 unfolding a function that is applied only to variables that have no
1076 unfolding (i.e. they are probably lambda bound): f x y z There is
1077 little point in inlining f here.
1078
1079 Generally, *values* (like (C a b) and (\x.e)) deserve discounts.  But
1080 we must look through lets, eg (let x = e in C a b), because the let will
1081 float, exposing the value, if we inline.  That makes it different to
1082 exprIsHNF.
1083
1084 Before 2009 we said it was interesting if the argument had *any* structure
1085 at all; i.e. (hasSomeUnfolding v).  But does too much inlining; see Trac #3016.
1086
1087 But we don't regard (f x y) as interesting, unless f is unsaturated.
1088 If it's saturated and f hasn't inlined, then it's probably not going
1089 to now!
1090
1091 Note [Conlike is interesting]
1092 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1093 Consider
1094         f d = ...((*) d x y)...
1095         ... f (df d')...
1096 where df is con-like. Then we'd really like to inline 'f' so that the
1097 rule for (*) (df d) can fire.  To do this 
1098   a) we give a discount for being an argument of a class-op (eg (*) d)
1099   b) we say that a con-like argument (eg (df d)) is interesting
1100
1101 \begin{code}
1102 data ArgSummary = TrivArg       -- Nothing interesting
1103                 | NonTrivArg    -- Arg has structure
1104                 | ValueArg      -- Arg is a con-app or PAP
1105                                 -- ..or con-like. Note [Conlike is interesting]
1106
1107 interestingArg :: CoreExpr -> ArgSummary
1108 -- See Note [Interesting arguments]
1109 interestingArg e = go e 0
1110   where
1111     -- n is # value args to which the expression is applied
1112     go (Lit {}) _          = ValueArg
1113     go (Var v)  n
1114        | isConLikeId v     = ValueArg   -- Experimenting with 'conlike' rather that
1115                                         --    data constructors here
1116        | idArity v > n     = ValueArg   -- Catches (eg) primops with arity but no unfolding
1117        | n > 0             = NonTrivArg -- Saturated or unknown call
1118        | conlike_unfolding = ValueArg   -- n==0; look for an interesting unfolding
1119                                         -- See Note [Conlike is interesting]
1120        | otherwise         = TrivArg    -- n==0, no useful unfolding
1121        where
1122          conlike_unfolding = isConLikeUnfolding (idUnfolding v)
1123
1124     go (Type _)          _ = TrivArg
1125     go (App fn (Type _)) n = go fn n    
1126     go (App fn _)        n = go fn (n+1)
1127     go (Note _ a)        n = go a n
1128     go (Cast e _)        n = go e n
1129     go (Lam v e)         n 
1130        | isTyCoVar v       = go e n
1131        | n>0               = go e (n-1)
1132        | otherwise         = ValueArg
1133     go (Let _ e)         n = case go e n of { ValueArg -> ValueArg; _ -> NonTrivArg }
1134     go (Case {})         _ = NonTrivArg
1135
1136 nonTriv ::  ArgSummary -> Bool
1137 nonTriv TrivArg = False
1138 nonTriv _       = True
1139 \end{code}
1140
1141 %************************************************************************
1142 %*                                                                      *
1143          exprIsConApp_maybe
1144 %*                                                                      *
1145 %************************************************************************
1146
1147 Note [exprIsConApp_maybe]
1148 ~~~~~~~~~~~~~~~~~~~~~~~~~
1149 exprIsConApp_maybe is a very important function.  There are two principal
1150 uses:
1151   * case e of { .... }
1152   * cls_op e, where cls_op is a class operation
1153
1154 In both cases you want to know if e is of form (C e1..en) where C is
1155 a data constructor.
1156
1157 However e might not *look* as if 
1158
1159 \begin{code}
1160 -- | Returns @Just (dc, [t1..tk], [x1..xn])@ if the argument expression is 
1161 -- a *saturated* constructor application of the form @dc t1..tk x1 .. xn@,
1162 -- where t1..tk are the *universally-qantified* type args of 'dc'
1163 exprIsConApp_maybe :: IdUnfoldingFun -> CoreExpr -> Maybe (DataCon, [Type], [CoreExpr])
1164
1165 exprIsConApp_maybe id_unf (Note _ expr)
1166   = exprIsConApp_maybe id_unf expr
1167         -- We ignore all notes.  For example,
1168         --      case _scc_ "foo" (C a b) of
1169         --                      C a b -> e
1170         -- should be optimised away, but it will be only if we look
1171         -- through the SCC note.
1172
1173 exprIsConApp_maybe id_unf (Cast expr co)
1174   =     -- Here we do the KPush reduction rule as described in the FC paper
1175         -- The transformation applies iff we have
1176         --      (C e1 ... en) `cast` co
1177         -- where co :: (T t1 .. tn) ~ to_ty
1178         -- The left-hand one must be a T, because exprIsConApp returned True
1179         -- but the right-hand one might not be.  (Though it usually will.)
1180
1181     case exprIsConApp_maybe id_unf expr of {
1182         Nothing                          -> Nothing ;
1183         Just (dc, _dc_univ_args, dc_args) -> 
1184
1185     let (_from_ty, to_ty) = coercionKind co
1186         dc_tc = dataConTyCon dc
1187     in
1188     case splitTyConApp_maybe to_ty of {
1189         Nothing -> Nothing ;
1190         Just (to_tc, to_tc_arg_tys) 
1191                 | dc_tc /= to_tc -> Nothing
1192                 -- These two Nothing cases are possible; we might see 
1193                 --      (C x y) `cast` (g :: T a ~ S [a]),
1194                 -- where S is a type function.  In fact, exprIsConApp
1195                 -- will probably not be called in such circumstances,
1196                 -- but there't nothing wrong with it 
1197
1198                 | otherwise  ->
1199     let
1200         tc_arity       = tyConArity dc_tc
1201         dc_univ_tyvars = dataConUnivTyVars dc
1202         dc_ex_tyvars   = dataConExTyVars dc
1203         arg_tys        = dataConRepArgTys dc
1204
1205         dc_eqs :: [(Type,Type)]   -- All equalities from the DataCon
1206         dc_eqs = [(mkTyVarTy tv, ty)   | (tv,ty) <- dataConEqSpec dc] ++
1207                  [getEqPredTys eq_pred | eq_pred <- dataConEqTheta dc]
1208
1209         (ex_args, rest1)    = splitAtList dc_ex_tyvars dc_args
1210         (co_args, val_args) = splitAtList dc_eqs rest1
1211
1212         -- Make the "theta" from Fig 3 of the paper
1213         gammas = decomposeCo tc_arity co
1214         theta  = zipOpenTvSubst (dc_univ_tyvars ++ dc_ex_tyvars)
1215                                 (gammas         ++ stripTypeArgs ex_args)
1216
1217           -- Cast the existential coercion arguments
1218         cast_co (ty1, ty2) (Type co) 
1219           = Type $ mkSymCoercion (substTy theta ty1)
1220                    `mkTransCoercion` co
1221                    `mkTransCoercion` (substTy theta ty2)
1222         cast_co _ other_arg = pprPanic "cast_co" (ppr other_arg)
1223         new_co_args = zipWith cast_co dc_eqs co_args
1224   
1225           -- Cast the value arguments (which include dictionaries)
1226         new_val_args = zipWith cast_arg arg_tys val_args
1227         cast_arg arg_ty arg = mkCoerce (substTy theta arg_ty) arg
1228     in
1229 #ifdef DEBUG
1230     let dump_doc = vcat [ppr dc,      ppr dc_univ_tyvars, ppr dc_ex_tyvars,
1231                          ppr arg_tys, ppr dc_args,        ppr _dc_univ_args,
1232                          ppr ex_args, ppr val_args]
1233     in
1234     ASSERT2( coreEqType _from_ty (mkTyConApp dc_tc _dc_univ_args), dump_doc )
1235     ASSERT2( all isTypeArg (ex_args ++ co_args), dump_doc )
1236     ASSERT2( equalLength val_args arg_tys, dump_doc )
1237 #endif
1238
1239     Just (dc, to_tc_arg_tys, ex_args ++ new_co_args ++ new_val_args)
1240     }}
1241
1242 exprIsConApp_maybe id_unf expr 
1243   = analyse expr [] 
1244   where
1245     analyse (App fun arg) args = analyse fun (arg:args)
1246     analyse fun@(Lam {})  args = beta fun [] args 
1247
1248     analyse (Var fun) args
1249         | Just con <- isDataConWorkId_maybe fun
1250         , count isValArg args == idArity fun
1251         , let (univ_ty_args, rest_args) = splitAtList (dataConUnivTyVars con) args
1252         = Just (con, stripTypeArgs univ_ty_args, rest_args)
1253
1254         -- Look through dictionary functions; see Note [Unfolding DFuns]
1255         | DFunUnfolding dfun_nargs con ops <- unfolding
1256         , let sat = length args == dfun_nargs    -- See Note [DFun arity check]
1257           in if sat then True else 
1258              pprTrace "Unsaturated dfun" (ppr fun <+> int dfun_nargs $$ ppr args) False   
1259         , let (dfun_tvs, _cls, dfun_res_tys) = tcSplitDFunTy (idType fun)
1260               subst = zipOpenTvSubst dfun_tvs (stripTypeArgs (takeList dfun_tvs args))
1261         = Just (con, substTys subst dfun_res_tys, 
1262                      [mkApps op args | op <- ops])
1263
1264         -- Look through unfoldings, but only cheap ones, because
1265         -- we are effectively duplicating the unfolding
1266         | Just rhs <- expandUnfolding_maybe unfolding
1267         = -- pprTrace "expanding" (ppr fun $$ ppr rhs) $
1268           analyse rhs args
1269         where
1270           unfolding = id_unf fun
1271
1272     analyse _ _ = Nothing
1273
1274     -----------
1275     beta (Lam v body) pairs (arg : args) 
1276         | isTypeArg arg
1277         = beta body ((v,arg):pairs) args 
1278
1279     beta (Lam {}) _ _    -- Un-saturated, or not a type lambda
1280         = Nothing
1281
1282     beta fun pairs args
1283         = analyse (substExpr (text "subst-expr-is-con-app") subst fun) args
1284         where
1285           subst = mkOpenSubst (mkInScopeSet (exprFreeVars fun)) pairs
1286           -- doc = vcat [ppr fun, ppr expr, ppr pairs, ppr args]
1287
1288
1289 stripTypeArgs :: [CoreExpr] -> [Type]
1290 stripTypeArgs args = ASSERT2( all isTypeArg args, ppr args )
1291                      [ty | Type ty <- args]
1292 \end{code}
1293
1294 Note [Unfolding DFuns]
1295 ~~~~~~~~~~~~~~~~~~~~~~
1296 DFuns look like
1297
1298   df :: forall a b. (Eq a, Eq b) -> Eq (a,b)
1299   df a b d_a d_b = MkEqD (a,b) ($c1 a b d_a d_b)
1300                                ($c2 a b d_a d_b)
1301
1302 So to split it up we just need to apply the ops $c1, $c2 etc
1303 to the very same args as the dfun.  It takes a little more work
1304 to compute the type arguments to the dictionary constructor.
1305
1306 Note [DFun arity check]
1307 ~~~~~~~~~~~~~~~~~~~~~~~
1308 Here we check that the total number of supplied arguments (inclding 
1309 type args) matches what the dfun is expecting.  This may be *less*
1310 than the ordinary arity of the dfun: see Note [DFun unfoldings] in CoreSyn