9d71b73422e21ddf857b711319c14e6f6c2136dd
[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 {-# OPTIONS -w #-}
19 -- The above warning supression flag is a temporary kludge.
20 -- While working on this module you are encouraged to remove it and fix
21 -- any warnings in the module. See
22 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
23 -- for details
24
25 module CoreUnfold (
26         Unfolding, UnfoldingGuidance,   -- Abstract types
27
28         noUnfolding, mkTopUnfolding, mkUnfolding, mkCompulsoryUnfolding, seqUnfolding,
29         evaldUnfolding, mkOtherCon, otherCons,
30         unfoldingTemplate, maybeUnfoldingTemplate,
31         isEvaldUnfolding, isValueUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
32         hasUnfolding, hasSomeUnfolding, neverUnfold,
33
34         couldBeSmallEnoughToInline, 
35         certainlyWillInline, smallEnoughToInline,
36
37         callSiteInline, CallContInfo(..)
38
39     ) where
40
41 #include "HsVersions.h"
42
43 import StaticFlags
44 import DynFlags
45 import CoreSyn
46 import PprCore          ()      -- Instances
47 import OccurAnal
48 import CoreUtils
49 import Id
50 import DataCon
51 import Literal
52 import PrimOp
53 import IdInfo
54 import Type
55 import PrelNames
56 import Bag
57 import FastTypes
58 import Outputable
59
60 import GHC.Exts         ( Int# )
61 \end{code}
62
63
64 %************************************************************************
65 %*                                                                      *
66 \subsection{Making unfoldings}
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 mkTopUnfolding expr = mkUnfolding True {- Top level -} expr
72
73 mkUnfolding top_lvl expr
74   = CoreUnfolding (occurAnalyseExpr expr)
75                   top_lvl
76
77                   (exprIsHNF expr)
78                         -- Already evaluated
79
80                   (exprIsCheap expr)
81                         -- OK to inline inside a lambda
82
83                   (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
84         -- Sometimes during simplification, there's a large let-bound thing     
85         -- which has been substituted, and so is now dead; so 'expr' contains
86         -- two copies of the thing while the occurrence-analysed expression doesn't
87         -- Nevertheless, we don't occ-analyse before computing the size because the
88         -- size computation bales out after a while, whereas occurrence analysis does not.
89         --
90         -- This can occasionally mean that the guidance is very pessimistic;
91         -- it gets fixed up next round
92
93 instance Outputable Unfolding where
94   ppr NoUnfolding = ptext SLIT("No unfolding")
95   ppr (OtherCon cs) = ptext SLIT("OtherCon") <+> ppr cs
96   ppr (CompulsoryUnfolding e) = ptext SLIT("Compulsory") <+> ppr e
97   ppr (CoreUnfolding e top hnf cheap g) 
98         = ptext SLIT("Unf") <+> sep [ppr top <+> ppr hnf <+> ppr cheap <+> ppr g, 
99                                      ppr e]
100
101 mkCompulsoryUnfolding expr      -- Used for things that absolutely must be unfolded
102   = CompulsoryUnfolding (occurAnalyseExpr expr)
103 \end{code}
104
105
106 %************************************************************************
107 %*                                                                      *
108 \subsection{The UnfoldingGuidance type}
109 %*                                                                      *
110 %************************************************************************
111
112 \begin{code}
113 instance Outputable UnfoldingGuidance where
114     ppr UnfoldNever     = ptext SLIT("NEVER")
115     ppr (UnfoldIfGoodArgs v cs size discount)
116       = hsep [ ptext SLIT("IF_ARGS"), int v,
117                brackets (hsep (map int cs)),
118                int size,
119                int discount ]
120 \end{code}
121
122
123 \begin{code}
124 calcUnfoldingGuidance
125         :: Int                  -- bomb out if size gets bigger than this
126         -> CoreExpr             -- expression to look at
127         -> UnfoldingGuidance
128 calcUnfoldingGuidance bOMB_OUT_SIZE expr
129   = case collect_val_bndrs expr of { (inline, val_binders, body) ->
130     let
131         n_val_binders = length val_binders
132
133         max_inline_size = n_val_binders+2
134         -- The idea is that if there is an INLINE pragma (inline is True)
135         -- and there's a big body, we give a size of n_val_binders+2.  This
136         -- This is just enough to fail the no-size-increase test in callSiteInline,
137         --   so that INLINE things don't get inlined into entirely boring contexts,
138         --   but no more.
139
140     in
141     case (sizeExpr (iUnbox bOMB_OUT_SIZE) val_binders body) of
142
143       TooBig 
144         | not inline -> UnfoldNever
145                 -- A big function with an INLINE pragma must
146                 -- have an UnfoldIfGoodArgs guidance
147         | otherwise  -> UnfoldIfGoodArgs n_val_binders
148                                          (map (const 0) val_binders)
149                                          max_inline_size 0
150
151       SizeIs size cased_args scrut_discount
152         -> UnfoldIfGoodArgs
153                         n_val_binders
154                         (map discount_for val_binders)
155                         final_size
156                         (iBox scrut_discount)
157         where        
158             boxed_size    = iBox size
159
160             final_size | inline     = boxed_size `min` max_inline_size
161                        | otherwise  = boxed_size
162
163                 -- Sometimes an INLINE thing is smaller than n_val_binders+2.
164                 -- A particular case in point is a constructor, which has size 1.
165                 -- We want to inline this regardless, hence the `min`
166
167             discount_for b = foldlBag (\acc (b',n) -> if b==b' then acc+n else acc) 
168                                       0 cased_args
169         }
170   where
171     collect_val_bndrs e = go False [] e
172         -- We need to be a bit careful about how we collect the
173         -- value binders.  In ptic, if we see 
174         --      __inline_me (\x y -> e)
175         -- We want to say "2 value binders".  Why?  So that 
176         -- we take account of information given for the arguments
177
178     go inline rev_vbs (Note InlineMe e)     = go True   rev_vbs     e
179     go inline rev_vbs (Lam b e) | isId b    = go inline (b:rev_vbs) e
180                                 | otherwise = go inline rev_vbs     e
181     go inline rev_vbs e                     = (inline, reverse rev_vbs, e)
182 \end{code}
183
184 \begin{code}
185 sizeExpr :: Int#            -- Bomb out if it gets bigger than this
186          -> [Id]            -- Arguments; we're interested in which of these
187                             -- get case'd
188          -> CoreExpr
189          -> ExprSize
190
191 sizeExpr bOMB_OUT_SIZE top_args expr
192   = size_up expr
193   where
194     size_up (Type t)          = sizeZero        -- Types cost nothing
195     size_up (Var v)           = sizeOne
196
197     size_up (Note InlineMe body) = sizeOne      -- Inline notes make it look very small
198         -- This can be important.  If you have an instance decl like this:
199         --      instance Foo a => Foo [a] where
200         --         {-# INLINE op1, op2 #-}
201         --         op1 = ...
202         --         op2 = ...
203         -- then we'll get a dfun which is a pair of two INLINE lambdas
204
205     size_up (Note _        body) = size_up body -- Other notes cost nothing
206     
207     size_up (Cast e _)           = size_up e
208
209     size_up (App fun (Type t)) = size_up fun
210     size_up (App fun arg)      = size_up_app fun [arg]
211
212     size_up (Lit lit)          = sizeN (litSize lit)
213
214     size_up (Lam b e) | isId b    = lamScrutDiscount (size_up e `addSizeN` 1)
215                       | otherwise = size_up e
216
217     size_up (Let (NonRec binder rhs) body)
218       = nukeScrutDiscount (size_up rhs)         `addSize`
219         size_up body                            `addSizeN`
220         (if isUnLiftedType (idType binder) then 0 else 1)
221                 -- For the allocation
222                 -- If the binder has an unlifted type there is no allocation
223
224     size_up (Let (Rec pairs) body)
225       = nukeScrutDiscount rhs_size              `addSize`
226         size_up body                            `addSizeN`
227         length pairs            -- For the allocation
228       where
229         rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
230
231     size_up (Case (Var v) _ _ alts) 
232         | v `elem` top_args             -- We are scrutinising an argument variable
233         = 
234 {-      I'm nuking this special case; BUT see the comment with case alternatives.
235
236         (a) It's too eager.  We don't want to inline a wrapper into a
237             context with no benefit.  
238             E.g.  \ x. f (x+x)          no point in inlining (+) here!
239
240         (b) It's ineffective. Once g's wrapper is inlined, its case-expressions 
241             aren't scrutinising arguments any more
242
243             case alts of
244
245                 [alt] -> size_up_alt alt `addSize` SizeIs 0# (unitBag (v, 1)) 0#
246                 -- We want to make wrapper-style evaluation look cheap, so that
247                 -- when we inline a wrapper it doesn't make call site (much) bigger
248                 -- Otherwise we get nasty phase ordering stuff: 
249                 --      f x = g x x
250                 --      h y = ...(f e)...
251                 -- If we inline g's wrapper, f looks big, and doesn't get inlined
252                 -- into h; if we inline f first, while it looks small, then g's 
253                 -- wrapper will get inlined later anyway.  To avoid this nasty
254                 -- ordering difference, we make (case a of (x,y) -> ...), 
255                 --  *where a is one of the arguments* look free.
256
257                 other -> 
258 -}
259                          alts_size (foldr addSize sizeOne alt_sizes)    -- The 1 is for the scrutinee
260                                    (foldr1 maxSize alt_sizes)
261
262                 -- Good to inline if an arg is scrutinised, because
263                 -- that may eliminate allocation in the caller
264                 -- And it eliminates the case itself
265
266         where
267           alt_sizes = map size_up_alt alts
268
269                 -- alts_size tries to compute a good discount for
270                 -- the case when we are scrutinising an argument variable
271           alts_size (SizeIs tot tot_disc tot_scrut)             -- Size of all alternatives
272                     (SizeIs max max_disc max_scrut)             -- Size of biggest alternative
273                 = SizeIs tot (unitBag (v, iBox (_ILIT 1 +# tot -# max)) `unionBags` max_disc) max_scrut
274                         -- If the variable is known, we produce a discount that
275                         -- will take us back to 'max', the size of rh largest alternative
276                         -- The 1+ is a little discount for reduced allocation in the caller
277           alts_size tot_size _ = tot_size
278
279     size_up (Case e _ _ alts) = nukeScrutDiscount (size_up e) `addSize` 
280                                  foldr (addSize . size_up_alt) sizeZero alts
281                 -- We don't charge for the case itself
282                 -- It's a strict thing, and the price of the call
283                 -- is paid by scrut.  Also consider
284                 --      case f x of DEFAULT -> e
285                 -- This is just ';'!  Don't charge for it.
286
287     ------------ 
288     size_up_app (App fun arg) args   
289         | isTypeArg arg              = size_up_app fun args
290         | otherwise                  = size_up_app fun (arg:args)
291     size_up_app fun           args   = foldr (addSize . nukeScrutDiscount . size_up) 
292                                              (size_up_fun fun args)
293                                              args
294
295         -- A function application with at least one value argument
296         -- so if the function is an argument give it an arg-discount
297         --
298         -- Also behave specially if the function is a build
299         --
300         -- Also if the function is a constant Id (constr or primop)
301         -- compute discounts specially
302     size_up_fun (Var fun) args
303       | fun `hasKey` buildIdKey   = buildSize
304       | fun `hasKey` augmentIdKey = augmentSize
305       | otherwise 
306       = case globalIdDetails fun of
307           DataConWorkId dc -> conSizeN dc (valArgCount args)
308
309           FCallId fc   -> sizeN opt_UF_DearOp
310           PrimOpId op  -> primOpSize op (valArgCount args)
311                           -- foldr addSize (primOpSize op) (map arg_discount args)
312                           -- At one time I tried giving an arg-discount if a primop 
313                           -- is applied to one of the function's arguments, but it's
314                           -- not good.  At the moment, any unlifted-type arg gets a
315                           -- 'True' for 'yes I'm evald', so we collect the discount even
316                           -- if we know nothing about it.  And just having it in a primop
317                           -- doesn't help at all if we don't know something more.
318
319           other        -> fun_discount fun `addSizeN` 
320                           (1 + length (filter (not . exprIsTrivial) args))
321                                 -- The 1+ is for the function itself
322                                 -- Add 1 for each non-trivial arg;
323                                 -- the allocation cost, as in let(rec)
324                                 -- Slight hack here: for constructors the args are almost always
325                                 --      trivial; and for primops they are almost always prim typed
326                                 --      We should really only count for non-prim-typed args in the
327                                 --      general case, but that seems too much like hard work
328
329     size_up_fun other args = size_up other
330
331     ------------ 
332     size_up_alt (con, bndrs, rhs) = size_up rhs
333         -- Don't charge for args, so that wrappers look cheap
334         -- (See comments about wrappers with Case)
335
336     ------------
337         -- We want to record if we're case'ing, or applying, an argument
338     fun_discount v | v `elem` top_args = SizeIs 0# (unitBag (v, opt_UF_FunAppDiscount)) 0#
339     fun_discount other                 = sizeZero
340
341     ------------
342         -- These addSize things have to be here because
343         -- I don't want to give them bOMB_OUT_SIZE as an argument
344
345     addSizeN TooBig          _  = TooBig
346     addSizeN (SizeIs n xs d) m  = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
347     
348     addSize TooBig            _                 = TooBig
349     addSize _                 TooBig            = TooBig
350     addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2) 
351         = mkSizeIs bOMB_OUT_SIZE (n1 +# n2) (xs `unionBags` ys) (d1 +# d2)
352 \end{code}
353
354 Code for manipulating sizes
355
356 \begin{code}
357 data ExprSize = TooBig
358               | SizeIs FastInt          -- Size found
359                        (Bag (Id,Int))   -- Arguments cased herein, and discount for each such
360                        FastInt          -- Size to subtract if result is scrutinised 
361                                         -- by a case expression
362
363 -- subtract the discount before deciding whether to bale out. eg. we
364 -- want to inline a large constructor application into a selector:
365 --      tup = (a_1, ..., a_99)
366 --      x = case tup of ...
367 --
368 mkSizeIs max n xs d | (n -# d) ># max = TooBig
369                     | otherwise       = SizeIs n xs d
370  
371 maxSize TooBig         _                                  = TooBig
372 maxSize _              TooBig                             = TooBig
373 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2  = s1
374                                               | otherwise = s2
375
376 sizeZero        = SizeIs (_ILIT 0)  emptyBag (_ILIT 0)
377 sizeOne         = SizeIs (_ILIT 1)  emptyBag (_ILIT 0)
378 sizeN n         = SizeIs (iUnbox n) emptyBag (_ILIT 0)
379 conSizeN dc n   
380   | isUnboxedTupleCon dc = SizeIs (_ILIT 0) emptyBag (iUnbox n +# _ILIT 1)
381   | otherwise            = SizeIs (_ILIT 1) emptyBag (iUnbox n +# _ILIT 1)
382         -- Treat constructors as size 1; we are keen to expose them
383         -- (and we charge separately for their args).  We can't treat
384         -- them as size zero, else we find that (iBox x) has size 1,
385         -- which is the same as a lone variable; and hence 'v' will 
386         -- always be replaced by (iBox x), where v is bound to iBox x.
387         --
388         -- However, unboxed tuples count as size zero
389         -- I found occasions where we had 
390         --      f x y z = case op# x y z of { s -> (# s, () #) }
391         -- and f wasn't getting inlined
392
393 primOpSize op n_args
394  | not (primOpIsDupable op) = sizeN opt_UF_DearOp
395  | not (primOpOutOfLine op) = sizeN (2 - n_args)
396         -- Be very keen to inline simple primops.
397         -- We give a discount of 1 for each arg so that (op# x y z) costs 2.
398         -- We can't make it cost 1, else we'll inline let v = (op# x y z) 
399         -- at every use of v, which is excessive.
400         --
401         -- A good example is:
402         --      let x = +# p q in C {x}
403         -- Even though x get's an occurrence of 'many', its RHS looks cheap,
404         -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
405  | otherwise                = sizeOne
406
407 buildSize = SizeIs (-2#) emptyBag 4#
408         -- We really want to inline applications of build
409         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
410         -- Indeed, we should add a result_discount becuause build is 
411         -- very like a constructor.  We don't bother to check that the
412         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
413         -- The "4" is rather arbitrary.
414
415 augmentSize = SizeIs (-2#) emptyBag 4#
416         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
417         -- e plus ys. The -2 accounts for the \cn 
418                                                 
419 nukeScrutDiscount (SizeIs n vs d) = SizeIs n vs 0#
420 nukeScrutDiscount TooBig          = TooBig
421
422 -- When we return a lambda, give a discount if it's used (applied)
423 lamScrutDiscount  (SizeIs n vs d) = case opt_UF_FunAppDiscount of { d -> SizeIs n vs (iUnbox d) }
424 lamScrutDiscount TooBig           = TooBig
425 \end{code}
426
427
428 %************************************************************************
429 %*                                                                      *
430 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
431 %*                                                                      *
432 %************************************************************************
433
434 We have very limited information about an unfolding expression: (1)~so
435 many type arguments and so many value arguments expected---for our
436 purposes here, we assume we've got those.  (2)~A ``size'' or ``cost,''
437 a single integer.  (3)~An ``argument info'' vector.  For this, what we
438 have at the moment is a Boolean per argument position that says, ``I
439 will look with great favour on an explicit constructor in this
440 position.'' (4)~The ``discount'' to subtract if the expression
441 is being scrutinised. 
442
443 Assuming we have enough type- and value arguments (if not, we give up
444 immediately), then we see if the ``discounted size'' is below some
445 (semi-arbitrary) threshold.  It works like this: for every argument
446 position where we're looking for a constructor AND WE HAVE ONE in our
447 hands, we get a (again, semi-arbitrary) discount [proportion to the
448 number of constructors in the type being scrutinized].
449
450 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
451 and the expression in question will evaluate to a constructor, we use
452 the computed discount size *for the result only* rather than
453 computing the argument discounts. Since we know the result of
454 the expression is going to be taken apart, discounting its size
455 is more accurate (see @sizeExpr@ above for how this discount size
456 is computed).
457
458 We use this one to avoid exporting inlinings that we ``couldn't possibly
459 use'' on the other side.  Can be overridden w/ flaggery.
460 Just the same as smallEnoughToInline, except that it has no actual arguments.
461
462 \begin{code}
463 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
464 couldBeSmallEnoughToInline threshold rhs = case calcUnfoldingGuidance threshold rhs of
465                                                 UnfoldNever -> False
466                                                 other       -> True
467
468 certainlyWillInline :: Unfolding -> Bool
469   -- Sees if the unfolding is pretty certain to inline  
470 certainlyWillInline (CoreUnfolding _ _ _ is_cheap (UnfoldIfGoodArgs n_vals _ size _))
471   = is_cheap && size - (n_vals +1) <= opt_UF_UseThreshold
472 certainlyWillInline other
473   = False
474
475 smallEnoughToInline :: Unfolding -> Bool
476 smallEnoughToInline (CoreUnfolding _ _ _ _ (UnfoldIfGoodArgs _ _ size _))
477   = size <= opt_UF_UseThreshold
478 smallEnoughToInline other
479   = False
480 \end{code}
481
482 %************************************************************************
483 %*                                                                      *
484 \subsection{callSiteInline}
485 %*                                                                      *
486 %************************************************************************
487
488 This is the key function.  It decides whether to inline a variable at a call site
489
490 callSiteInline is used at call sites, so it is a bit more generous.
491 It's a very important function that embodies lots of heuristics.
492 A non-WHNF can be inlined if it doesn't occur inside a lambda,
493 and occurs exactly once or 
494     occurs once in each branch of a case and is small
495
496 If the thing is in WHNF, there's no danger of duplicating work, 
497 so we can inline if it occurs once, or is small
498
499 NOTE: we don't want to inline top-level functions that always diverge.
500 It just makes the code bigger.  Tt turns out that the convenient way to prevent
501 them inlining is to give them a NOINLINE pragma, which we do in 
502 StrictAnal.addStrictnessInfoToTopId
503
504 \begin{code}
505 callSiteInline :: DynFlags
506                -> Bool                  -- True <=> the Id can be inlined
507                -> Id                    -- The Id
508                -> Bool                  -- True if there are are no arguments at all (incl type args)
509                -> [Bool]                -- One for each value arg; True if it is interesting
510                -> CallContInfo          -- True <=> continuation is interesting
511                -> Maybe CoreExpr        -- Unfolding, if any
512
513
514 data CallContInfo = BoringCont          
515                   | InterestingCont     -- Somewhat interesting
516                   | CaseCont            -- Very interesting; the argument of a case
517                                         -- that decomposes its scrutinee
518
519 instance Outputable CallContInfo where
520   ppr BoringCont      = ptext SLIT("BoringCont")
521   ppr InterestingCont = ptext SLIT("InterestingCont")
522   ppr CaseCont        = ptext SLIT("CaseCont")
523
524 callSiteInline dflags active_inline id lone_variable arg_infos cont_info
525   = case idUnfolding id of {
526         NoUnfolding -> Nothing ;
527         OtherCon cs -> Nothing ;
528
529         CompulsoryUnfolding unf_template -> Just unf_template ;
530                 -- CompulsoryUnfolding => there is no top-level binding
531                 -- for these things, so we must inline it.
532                 -- Only a couple of primop-like things have 
533                 -- compulsory unfoldings (see MkId.lhs).
534                 -- We don't allow them to be inactive
535
536         CoreUnfolding unf_template is_top is_value is_cheap guidance ->
537
538     let
539         result | yes_or_no = Just unf_template
540                | otherwise = Nothing
541
542         n_val_args  = length arg_infos
543
544         yes_or_no = active_inline && is_cheap && consider_safe
545                 -- We consider even the once-in-one-branch
546                 -- occurrences, because they won't all have been
547                 -- caught by preInlineUnconditionally.  In particular,
548                 -- if the occurrence is once inside a lambda, and the
549                 -- rhs is cheap but not a manifest lambda, then
550                 -- pre-inline will not have inlined it for fear of
551                 -- invalidating the occurrence info in the rhs.
552
553         consider_safe
554                 -- consider_safe decides whether it's a good idea to
555                 -- inline something, given that there's no
556                 -- work-duplication issue (the caller checks that).
557           = case guidance of
558               UnfoldNever  -> False
559               UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
560                   | enough_args && size <= (n_vals_wanted + 1)
561                         -- Inline unconditionally if there no size increase
562                         -- Size of call is n_vals_wanted (+1 for the function)
563                   -> True
564
565                   | otherwise
566                   -> some_benefit && small_enough
567
568                   where
569                     enough_args = n_val_args >= n_vals_wanted
570
571                     some_benefit = or arg_infos || really_interesting_cont
572                                 -- There must be something interesting
573                                 -- about some argument, or the result
574                                 -- context, to make it worth inlining
575
576                     really_interesting_cont 
577                         | n_val_args <  n_vals_wanted = False   -- Too few args
578                         | n_val_args == n_vals_wanted = interesting_saturated_call
579                         | otherwise                   = True    -- Extra args
580                         -- really_interesting_cont tells if the result of the
581                         -- call is in an interesting context.
582
583                     interesting_saturated_call 
584                         = case cont_info of
585                             BoringCont -> not is_top && n_vals_wanted > 0       -- Note [Nested functions] 
586                             CaseCont   -> not lone_variable || not is_value     -- Note [Lone variables]
587                             InterestingCont -> n_vals_wanted > 0
588
589                     small_enough = (size - discount) <= opt_UF_UseThreshold
590                     discount = computeDiscount n_vals_wanted arg_discounts 
591                                                res_discount' arg_infos
592                     res_discount' = case cont_info of
593                                         BoringCont      -> 0
594                                         CaseCont        -> res_discount
595                                         InterestingCont -> 4 `min` res_discount
596                         -- res_discount can be very large when a function returns
597                         -- construtors; but we only want to invoke that large discount
598                         -- when there's a case continuation.
599                         -- Otherwise we, rather arbitrarily, threshold it.  Yuk.
600                         -- But we want to aovid inlining large functions that return 
601                         -- constructors into contexts that are simply "interesting"
602                 
603     in    
604     if dopt Opt_D_dump_inlinings dflags then
605         pprTrace "Considering inlining"
606                  (ppr id <+> vcat [text "active:" <+> ppr active_inline,
607                                    text "arg infos" <+> ppr arg_infos,
608                                    text "interesting continuation" <+> ppr cont_info,
609                                    text "is value:" <+> ppr is_value,
610                                    text "is cheap:" <+> ppr is_cheap,
611                                    text "guidance" <+> ppr guidance,
612                                    text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"])
613                   result
614     else
615     result
616     }
617 \end{code}
618
619 Note [Nested functions]
620 ~~~~~~~~~~~~~~~~~~~~~~~
621 If a function has a nested defn we also record some-benefit, on the
622 grounds that we are often able to eliminate the binding, and hence the
623 allocation, for the function altogether; this is good for join points.
624 But this only makes sense for *functions*; inlining a constructor
625 doesn't help allocation unless the result is scrutinised.  UNLESS the
626 constructor occurs just once, albeit possibly in multiple case
627 branches.  Then inlining it doesn't increase allocation, but it does
628 increase the chance that the constructor won't be allocated at all in
629 the branches that don't use it.
630
631 Note [Lone variables]
632 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
633 The "lone-variable" case is important.  I spent ages messing about
634 with unsatisfactory varaints, but this is nice.  The idea is that if a
635 variable appears all alone
636         as an arg of lazy fn, or rhs    Stop
637         as scrutinee of a case          Select
638         as arg of a strict fn           ArgOf
639 AND
640         it is bound to a value
641 then we should not inline it (unless there is some other reason,
642 e.g. is is the sole occurrence).  That is what is happening at 
643 the use of 'lone_variable' in 'interesting_saturated_call'.
644
645 Why?  At least in the case-scrutinee situation, turning
646         let x = (a,b) in case x of y -> ...
647 into
648         let x = (a,b) in case (a,b) of y -> ...
649 and thence to 
650         let x = (a,b) in let y = (a,b) in ...
651 is bad if the binding for x will remain.
652
653 Another example: I discovered that strings
654 were getting inlined straight back into applications of 'error'
655 because the latter is strict.
656         s = "foo"
657         f = \x -> ...(error s)...
658
659 Fundamentally such contexts should not encourage inlining because the
660 context can ``see'' the unfolding of the variable (e.g. case or a
661 RULE) so there's no gain.  If the thing is bound to a value.
662
663 However, watch out:
664
665  * Consider this:
666         foo = _inline_ (\n. [n])
667         bar = _inline_ (foo 20)
668         baz = \n. case bar of { (m:_) -> m + n }
669    Here we really want to inline 'bar' so that we can inline 'foo'
670    and the whole thing unravels as it should obviously do.  This is 
671    important: in the NDP project, 'bar' generates a closure data
672    structure rather than a list. 
673
674  * Even a type application or coercion isn't a lone variable.
675    Consider
676         case $fMonadST @ RealWorld of { :DMonad a b c -> c }
677    We had better inline that sucker!  The case won't see through it.
678
679    For now, I'm treating treating a variable applied to types 
680    in a *lazy* context "lone". The motivating example was
681         f = /\a. \x. BIG
682         g = /\a. \y.  h (f a)
683    There's no advantage in inlining f here, and perhaps
684    a significant disadvantage.  Hence some_val_args in the Stop case
685
686 \begin{code}
687 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Int
688 computeDiscount n_vals_wanted arg_discounts result_discount arg_infos
689         -- We multiple the raw discounts (args_discount and result_discount)
690         -- ty opt_UnfoldingKeenessFactor because the former have to do with
691         --  *size* whereas the discounts imply that there's some extra 
692         --  *efficiency* to be gained (e.g. beta reductions, case reductions) 
693         -- by inlining.
694
695         -- we also discount 1 for each argument passed, because these will
696         -- reduce with the lambdas in the function (we count 1 for a lambda
697         -- in size_up).
698   = 1 +                 -- Discount of 1 because the result replaces the call
699                         -- so we count 1 for the function itself
700     length (take n_vals_wanted arg_infos) +
701                         -- Discount of 1 for each arg supplied, because the 
702                         -- result replaces the call
703     round (opt_UF_KeenessFactor * 
704            fromIntegral (arg_discount + result_discount))
705   where
706     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
707
708     mk_arg_discount discount is_evald | is_evald  = discount
709                                       | otherwise = 0
710 \end{code}