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