[project @ 2000-05-24 15:47:13 by simonpj]
[ghc-hetmet.git] / ghc / 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         mkOtherCon, otherCons,
21         unfoldingTemplate, maybeUnfoldingTemplate,
22         isEvaldUnfolding, isValueUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
23         hasUnfolding, hasSomeUnfolding,
24
25         couldBeSmallEnoughToInline, 
26         certainlyWillInline, 
27         okToUnfoldInHiFile,
28
29         callSiteInline, blackListed
30     ) where
31
32 #include "HsVersions.h"
33
34 import CmdLineOpts      ( opt_UF_CreationThreshold,
35                           opt_UF_UseThreshold,
36                           opt_UF_ScrutConDiscount,
37                           opt_UF_FunAppDiscount,
38                           opt_UF_PrimArgDiscount,
39                           opt_UF_KeenessFactor,
40                           opt_UF_CheapOp, opt_UF_DearOp,
41                           opt_UnfoldCasms, opt_PprStyle_Debug,
42                           opt_D_dump_inlinings
43                         )
44 import CoreSyn
45 import PprCore          ( pprCoreExpr )
46 import OccurAnal        ( occurAnalyseGlobalExpr )
47 import BinderInfo       ( )
48 import CoreUtils        ( exprIsValue, exprIsCheap, exprIsBottom, exprIsTrivial )
49 import Id               ( Id, idType, idFlavour, idUnique, isId, idWorkerInfo,
50                           idSpecialisation, idInlinePragma, idUnfolding,
51                           isPrimOpId_maybe
52                         )
53 import VarSet
54 import Name             ( isLocallyDefined )
55 import Literal          ( isLitLitLit )
56 import PrimOp           ( PrimOp(..), primOpIsDupable, primOpOutOfLine, ccallIsCasm )
57 import IdInfo           ( ArityInfo(..), InlinePragInfo(..), OccInfo(..), IdFlavour(..), CprInfo(..), 
58                           insideLam, workerExists, isNeverInlinePrag
59                         )
60 import TyCon            ( tyConFamilySize )
61 import Type             ( splitFunTy_maybe, isUnLiftedType )
62 import Unique           ( Unique, buildIdKey, augmentIdKey )
63 import Maybes           ( maybeToBool )
64 import Bag
65 import List             ( maximumBy )
66 import Util             ( isIn, lengthExceeds )
67 import Outputable
68
69 #if __GLASGOW_HASKELL__ >= 404
70 import GlaExts          ( fromInt )
71 #endif
72 \end{code}
73
74
75 %************************************************************************
76 %*                                                                      *
77 \subsection{Making unfoldings}
78 %*                                                                      *
79 %************************************************************************
80
81 \begin{code}
82 mkTopUnfolding expr = mkUnfolding True {- Top level -} expr
83
84 mkUnfolding top_lvl expr
85   = CoreUnfolding (occurAnalyseGlobalExpr expr)
86                   top_lvl
87                   (exprIsCheap expr)
88                   (exprIsValue expr)
89                   (exprIsBottom expr)
90                   (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
91         -- Sometimes during simplification, there's a large let-bound thing     
92         -- which has been substituted, and so is now dead; so 'expr' contains
93         -- two copies of the thing while the occurrence-analysed expression doesn't
94         -- Nevertheless, we don't occ-analyse before computing the size because the
95         -- size computation bales out after a while, whereas occurrence analysis does not.
96         --
97         -- This can occasionally mean that the guidance is very pessimistic;
98         -- it gets fixed up next round
99
100 mkCompulsoryUnfolding expr      -- Used for things that absolutely must be unfolded
101   = CompulsoryUnfolding (occurAnalyseGlobalExpr expr)
102 \end{code}
103
104
105 %************************************************************************
106 %*                                                                      *
107 \subsection{The UnfoldingGuidance type}
108 %*                                                                      *
109 %************************************************************************
110
111 \begin{code}
112 instance Outputable UnfoldingGuidance where
113     ppr UnfoldNever     = ptext SLIT("NEVER")
114     ppr (UnfoldIfGoodArgs v cs size discount)
115       = hsep [ ptext SLIT("IF_ARGS"), int v,
116                brackets (hsep (map int cs)),
117                int size,
118                int discount ]
119 \end{code}
120
121
122 \begin{code}
123 calcUnfoldingGuidance
124         :: Int                  -- bomb out if size gets bigger than this
125         -> CoreExpr             -- expression to look at
126         -> UnfoldingGuidance
127 calcUnfoldingGuidance bOMB_OUT_SIZE expr
128   = case collect_val_bndrs expr of { (inline, val_binders, body) ->
129     let
130         n_val_binders = length val_binders
131
132         max_inline_size = n_val_binders+2
133         -- The idea is that if there is an INLINE pragma (inline is True)
134         -- and there's a big body, we give a size of n_val_binders+2.  This
135         -- This is just enough to fail the no-size-increase test in callSiteInline,
136         --   so that INLINE things don't get inlined into entirely boring contexts,
137         --   but no more.
138
139     in
140     case (sizeExpr bOMB_OUT_SIZE val_binders body) of
141
142       TooBig 
143         | not inline -> UnfoldNever
144                 -- A big function with an INLINE pragma must
145                 -- have an UnfoldIfGoodArgs guidance
146         | inline     -> UnfoldIfGoodArgs n_val_binders
147                                          (map (const 0) val_binders)
148                                          max_inline_size 0
149
150       SizeIs size cased_args scrut_discount
151         -> UnfoldIfGoodArgs
152                         n_val_binders
153                         (map discount_for val_binders)
154                         final_size
155                         (I# scrut_discount)
156         where        
157             boxed_size    = I# size
158
159             final_size | inline     = boxed_size `min` max_inline_size
160                        | otherwise  = boxed_size
161
162                 -- Sometimes an INLINE thing is smaller than n_val_binders+2.
163                 -- A particular case in point is a constructor, which has size 1.
164                 -- We want to inline this regardless, hence the `min`
165
166             discount_for b = foldlBag (\acc (b',n) -> if b==b' then acc+n else acc) 
167                                       0 cased_args
168         }
169   where
170     collect_val_bndrs e = go False [] e
171         -- We need to be a bit careful about how we collect the
172         -- value binders.  In ptic, if we see 
173         --      __inline_me (\x y -> e)
174         -- We want to say "2 value binders".  Why?  So that 
175         -- we take account of information given for the arguments
176
177     go inline rev_vbs (Note InlineMe e)     = go True   rev_vbs     e
178     go inline rev_vbs (Lam b e) | isId b    = go inline (b:rev_vbs) e
179                                 | otherwise = go inline rev_vbs     e
180     go inline rev_vbs e                     = (inline, reverse rev_vbs, e)
181 \end{code}
182
183 \begin{code}
184 sizeExpr :: Int             -- Bomb out if it gets bigger than this
185          -> [Id]            -- Arguments; we're interested in which of these
186                             -- get case'd
187          -> CoreExpr
188          -> ExprSize
189
190 sizeExpr (I# bOMB_OUT_SIZE) top_args expr
191   = size_up expr
192   where
193     size_up (Type t)          = sizeZero        -- Types cost nothing
194     size_up (Var v)           = sizeOne
195
196     size_up (Note _ body)     = size_up body    -- Notes cost nothing
197
198     size_up (App fun (Type t))  = size_up fun
199     size_up (App fun arg)     = size_up_app fun [arg]
200
201     size_up (Lit lit) = sizeOne
202
203     size_up (Lam b e) | isId b    = lamScrutDiscount (size_up e `addSizeN` 1)
204                       | otherwise = size_up e
205
206     size_up (Let (NonRec binder rhs) body)
207       = nukeScrutDiscount (size_up rhs)         `addSize`
208         size_up body                            `addSizeN`
209         (if isUnLiftedType (idType binder) then 0 else 1)
210                 -- For the allocation
211                 -- If the binder has an unlifted type there is no allocation
212
213     size_up (Let (Rec pairs) body)
214       = nukeScrutDiscount rhs_size              `addSize`
215         size_up body                            `addSizeN`
216         length pairs            -- For the allocation
217       where
218         rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
219
220         -- We want to make wrapper-style evaluation look cheap, so that
221         -- when we inline a wrapper it doesn't make call site (much) bigger
222         -- Otherwise we get nasty phase ordering stuff: 
223         --      f x = g x x
224         --      h y = ...(f e)...
225         -- If we inline g's wrapper, f looks big, and doesn't get inlined
226         -- into h; if we inline f first, while it looks small, then g's 
227         -- wrapper will get inlined later anyway.  To avoid this nasty
228         -- ordering difference, we make (case a of (x,y) -> ...) look free.
229     size_up (Case (Var v) _ [alt]) 
230         | v `elem` top_args
231         = size_up_alt alt `addSize` SizeIs 0# (unitBag (v, 1)) 0#
232                 -- Good to inline if an arg is scrutinised, because
233                 -- that may eliminate allocation in the caller
234                 -- And it eliminates the case itself
235         | otherwise     
236         = size_up_alt alt
237
238         -- Scrutinising one of the argument variables,
239         -- with more than one alternative
240     size_up (Case (Var v) _ alts)
241         | v `elem` top_args
242         = alts_size (foldr addSize sizeOne alt_sizes)   -- The 1 is for the scrutinee
243                     (foldr1 maxSize alt_sizes)
244         where
245           v_in_args = v `elem` top_args
246           alt_sizes = map size_up_alt alts
247
248           alts_size (SizeIs tot tot_disc tot_scrut)             -- Size of all alternatives
249                     (SizeIs max max_disc max_scrut)             -- Size of biggest alternative
250                 = SizeIs tot (unitBag (v, I# (1# +# tot -# max)) `unionBags` max_disc) max_scrut
251                         -- If the variable is known, we produce a discount that
252                         -- will take us back to 'max', the size of rh largest alternative
253                         -- The 1+ is a little discount for reduced allocation in the caller
254
255           alts_size tot_size _ = tot_size
256
257
258     size_up (Case e _ alts) = nukeScrutDiscount (size_up e) `addSize` 
259                               foldr (addSize . size_up_alt) sizeZero alts
260                 -- We don't charge for the case itself
261                 -- It's a strict thing, and the price of the call
262                 -- is paid by scrut.  Also consider
263                 --      case f x of DEFAULT -> e
264                 -- This is just ';'!  Don't charge for it.
265
266     ------------ 
267     size_up_app (App fun arg) args   
268         | isTypeArg arg              = size_up_app fun args
269         | otherwise                  = size_up_app fun (arg:args)
270     size_up_app fun           args   = foldr (addSize . nukeScrutDiscount . size_up) 
271                                              (size_up_fun fun args)
272                                              args
273
274         -- A function application with at least one value argument
275         -- so if the function is an argument give it an arg-discount
276         --
277         -- Also behave specially if the function is a build
278         --
279         -- Also if the function is a constant Id (constr or primop)
280         -- compute discounts specially
281     size_up_fun (Var fun) args
282       | idUnique fun == buildIdKey   = buildSize
283       | idUnique fun == augmentIdKey = augmentSize
284       | otherwise 
285       = case idFlavour fun of
286           DataConId dc -> conSizeN (valArgCount args)
287
288           PrimOpId op  -> primOpSize op (valArgCount args)
289                           -- foldr addSize (primOpSize op) (map arg_discount args)
290                           -- At one time I tried giving an arg-discount if a primop 
291                           -- is applied to one of the function's arguments, but it's
292                           -- not good.  At the moment, any unlifted-type arg gets a
293                           -- 'True' for 'yes I'm evald', so we collect the discount even
294                           -- if we know nothing about it.  And just having it in a primop
295                           -- doesn't help at all if we don't know something more.
296
297           other        -> fun_discount fun `addSizeN` 
298                           (1 + length (filter (not . exprIsTrivial) args))
299                                 -- The 1+ is for the function itself
300                                 -- Add 1 for each non-trivial arg;
301                                 -- the allocation cost, as in let(rec)
302                                 -- Slight hack here: for constructors the args are almost always
303                                 --      trivial; and for primops they are almost always prim typed
304                                 --      We should really only count for non-prim-typed args in the
305                                 --      general case, but that seems too much like hard work
306
307     size_up_fun other args = size_up other
308
309     ------------ 
310     size_up_alt (con, bndrs, rhs) = size_up rhs
311             -- Don't charge for args, so that wrappers look cheap
312
313     ------------
314         -- We want to record if we're case'ing, or applying, an argument
315     fun_discount v | v `elem` top_args = SizeIs 0# (unitBag (v, opt_UF_FunAppDiscount)) 0#
316     fun_discount other                    = sizeZero
317
318     ------------
319         -- These addSize things have to be here because
320         -- I don't want to give them bOMB_OUT_SIZE as an argument
321
322     addSizeN TooBig          _      = TooBig
323     addSizeN (SizeIs n xs d) (I# m)
324       | n_tot ># bOMB_OUT_SIZE      = TooBig
325       | otherwise                   = SizeIs n_tot xs d
326       where
327         n_tot = n +# m
328     
329     addSize TooBig _ = TooBig
330     addSize _ TooBig = TooBig
331     addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2)
332       | n_tot ># bOMB_OUT_SIZE = TooBig
333       | otherwise              = SizeIs n_tot xys d_tot
334       where
335         n_tot = n1 +# n2
336         d_tot = d1 +# d2
337         xys   = xs `unionBags` ys
338 \end{code}
339
340 Code for manipulating sizes
341
342 \begin{code}
343
344 data ExprSize = TooBig
345               | SizeIs Int#             -- Size found
346                        (Bag (Id,Int))   -- Arguments cased herein, and discount for each such
347                        Int#             -- Size to subtract if result is scrutinised 
348                                         -- by a case expression
349
350 isTooBig TooBig = True
351 isTooBig _      = False
352
353 maxSize TooBig         _                                  = TooBig
354 maxSize _              TooBig                             = TooBig
355 maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2  = s1
356                                               | otherwise = s2
357
358 sizeZero        = SizeIs 0# emptyBag 0#
359 sizeOne         = SizeIs 1# emptyBag 0#
360 sizeTwo         = SizeIs 2# emptyBag 0#
361 sizeN (I# n)    = SizeIs n  emptyBag 0#
362 conSizeN (I# n) = SizeIs 1# emptyBag (n +# 1#)
363         -- Treat constructors as size 1; we are keen to expose them
364         -- (and we charge separately for their args).  We can't treat
365         -- them as size zero, else we find that (I# x) has size 1,
366         -- which is the same as a lone variable; and hence 'v' will 
367         -- always be replaced by (I# x), where v is bound to I# x.
368
369 primOpSize op n_args
370  | not (primOpIsDupable op) = sizeN opt_UF_DearOp
371  | not (primOpOutOfLine op) = sizeZero                  -- These are good to inline
372  | otherwise                = sizeOne
373
374 buildSize = SizeIs (-2#) emptyBag 4#
375         -- We really want to inline applications of build
376         -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
377         -- Indeed, we should add a result_discount becuause build is 
378         -- very like a constructor.  We don't bother to check that the
379         -- build is saturated (it usually is).  The "-2" discounts for the \c n, 
380         -- The "4" is rather arbitrary.
381
382 augmentSize = SizeIs (-2#) emptyBag 4#
383         -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
384         -- e plus ys. The -2 accounts for the \cn 
385                                                 
386 nukeScrutDiscount (SizeIs n vs d) = SizeIs n vs 0#
387 nukeScrutDiscount TooBig          = TooBig
388
389 -- When we return a lambda, give a discount if it's used (applied)
390 lamScrutDiscount  (SizeIs n vs d) = case opt_UF_FunAppDiscount of { I# d -> SizeIs n vs d }
391 lamScrutDiscount TooBig           = TooBig
392 \end{code}
393
394
395 %************************************************************************
396 %*                                                                      *
397 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
398 %*                                                                      *
399 %************************************************************************
400
401 We have very limited information about an unfolding expression: (1)~so
402 many type arguments and so many value arguments expected---for our
403 purposes here, we assume we've got those.  (2)~A ``size'' or ``cost,''
404 a single integer.  (3)~An ``argument info'' vector.  For this, what we
405 have at the moment is a Boolean per argument position that says, ``I
406 will look with great favour on an explicit constructor in this
407 position.'' (4)~The ``discount'' to subtract if the expression
408 is being scrutinised. 
409
410 Assuming we have enough type- and value arguments (if not, we give up
411 immediately), then we see if the ``discounted size'' is below some
412 (semi-arbitrary) threshold.  It works like this: for every argument
413 position where we're looking for a constructor AND WE HAVE ONE in our
414 hands, we get a (again, semi-arbitrary) discount [proportion to the
415 number of constructors in the type being scrutinized].
416
417 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
418 and the expression in question will evaluate to a constructor, we use
419 the computed discount size *for the result only* rather than
420 computing the argument discounts. Since we know the result of
421 the expression is going to be taken apart, discounting its size
422 is more accurate (see @sizeExpr@ above for how this discount size
423 is computed).
424
425 We use this one to avoid exporting inlinings that we ``couldn't possibly
426 use'' on the other side.  Can be overridden w/ flaggery.
427 Just the same as smallEnoughToInline, except that it has no actual arguments.
428
429 \begin{code}
430 couldBeSmallEnoughToInline :: Int -> CoreExpr -> Bool
431 couldBeSmallEnoughToInline threshold rhs = case calcUnfoldingGuidance threshold rhs of
432                                                 UnfoldNever -> False
433                                                 other       -> True
434
435 certainlyWillInline :: Id -> Bool
436         -- Sees if the Id is pretty certain to inline   
437 certainlyWillInline v
438   = case idUnfolding v of
439
440         CoreUnfolding _ _ _ is_value _ g@(UnfoldIfGoodArgs n_vals _ size _)
441            ->    is_value 
442               && size - (n_vals +1) <= opt_UF_UseThreshold
443
444         other -> False
445 \end{code}
446
447 @okToUnfoldInHifile@ is used when emitting unfolding info into an interface
448 file to determine whether an unfolding candidate really should be unfolded.
449 The predicate is needed to prevent @_casm_@s (+ lit-lits) from being emitted
450 into interface files. 
451
452 The reason for inlining expressions containing _casm_s into interface files
453 is that these fragments of C are likely to mention functions/#defines that
454 will be out-of-scope when inlined into another module. This is not an
455 unfixable problem for the user (just need to -#include the approp. header
456 file), but turning it off seems to the simplest thing to do.
457
458 \begin{code}
459 okToUnfoldInHiFile :: CoreExpr -> Bool
460 okToUnfoldInHiFile e = opt_UnfoldCasms || go e
461  where
462     -- Race over an expression looking for CCalls..
463     go (Var v)                = case isPrimOpId_maybe v of
464                                   Just op -> okToUnfoldPrimOp op
465                                   Nothing -> True
466     go (Lit lit)              = not (isLitLitLit lit)
467     go (App fun arg)          = go fun && go arg
468     go (Lam _ body)           = go body
469     go (Let binds body)       = and (map go (body :rhssOfBind binds))
470     go (Case scrut bndr alts) = and (map go (scrut:rhssOfAlts alts))
471     go (Note _ body)          = go body
472     go (Type _)               = True
473
474     -- ok to unfold a PrimOp as long as it's not a _casm_
475     okToUnfoldPrimOp (CCallOp ccall) = not (ccallIsCasm ccall)
476     okToUnfoldPrimOp _               = True
477 \end{code}
478
479
480 %************************************************************************
481 %*                                                                      *
482 \subsection{callSiteInline}
483 %*                                                                      *
484 %************************************************************************
485
486 This is the key function.  It decides whether to inline a variable at a call site
487
488 callSiteInline is used at call sites, so it is a bit more generous.
489 It's a very important function that embodies lots of heuristics.
490 A non-WHNF can be inlined if it doesn't occur inside a lambda,
491 and occurs exactly once or 
492     occurs once in each branch of a case and is small
493
494 If the thing is in WHNF, there's no danger of duplicating work, 
495 so we can inline if it occurs once, or is small
496
497 NOTE: we don't want to inline top-level functions that always diverge.
498 It just makes the code bigger.  Tt turns out that the convenient way to prevent
499 them inlining is to give them a NOINLINE pragma, which we do in 
500 StrictAnal.addStrictnessInfoToTopId
501
502 \begin{code}
503 callSiteInline :: Bool                  -- True <=> the Id is black listed
504                -> Bool                  -- 'inline' note at call site
505                -> OccInfo
506                -> Id                    -- The Id
507                -> [Bool]                -- One for each value arg; True if it is interesting
508                -> Bool                  -- True <=> continuation is interesting
509                -> Maybe CoreExpr        -- Unfolding, if any
510
511
512 callSiteInline black_listed inline_call occ id arg_infos interesting_cont
513   = case idUnfolding id of {
514         NoUnfolding -> Nothing ;
515         OtherCon cs -> Nothing ;
516         CompulsoryUnfolding unf_template | black_listed -> Nothing 
517                                          | otherwise    -> Just unf_template ;
518                 -- Constructors have compulsory unfoldings, but
519                 -- may have rules, in which case they are 
520                 -- black listed till later
521         CoreUnfolding unf_template is_top is_cheap is_value is_bot guidance ->
522
523     let
524         result | yes_or_no = Just unf_template
525                | otherwise = Nothing
526
527         n_val_args  = length arg_infos
528
529         ok_inside_lam = is_value || is_bot || (is_cheap && not is_top)
530                                 -- I'm experimenting with is_cheap && not is_top
531
532         yes_or_no 
533           | black_listed = False
534           | otherwise    = case occ of
535                                 IAmDead              -> pprTrace "callSiteInline: dead" (ppr id) False
536                                 IAmALoopBreaker      -> False
537                                 OneOcc in_lam one_br -> (not in_lam || ok_inside_lam) && consider_safe in_lam True  one_br
538                                 NoOccInfo            -> ok_inside_lam                 && consider_safe True   False False
539
540         consider_safe in_lam once once_in_one_branch
541                 -- consider_safe decides whether it's a good idea to inline something,
542                 -- given that there's no work-duplication issue (the caller checks that).
543                 -- once_in_one_branch = True means there's a unique textual occurrence
544           | inline_call  = True
545
546           | once_in_one_branch
547                 -- Be very keen to inline something if this is its unique occurrence:
548                 --
549                 --   a) Inlining gives a good chance of eliminating the original 
550                 --      binding (and hence the allocation) for the thing.  
551                 --      (Provided it's not a top level binding, in which case the 
552                 --       allocation costs nothing.)
553                 --
554                 --   b) Inlining a function that is called only once exposes the 
555                 --      body function to the call site.
556                 --
557                 -- The only time we hold back is when substituting inside a lambda;
558                 -- then if the context is totally uninteresting (not applied, not scrutinised)
559                 -- there is no point in substituting because it might just increase allocation,
560                 -- by allocating the function itself many times
561                 --
562                 -- Note: there used to be a '&& not top_level' in the guard above,
563                 --       but that stopped us inlining top-level functions used only once,
564                 --       which is stupid
565           = not in_lam || not (null arg_infos) || interesting_cont
566
567           | otherwise
568           = case guidance of
569               UnfoldNever  -> False ;
570               UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
571
572                   | enough_args && size <= (n_vals_wanted + 1)
573                         -- No size increase
574                         -- Size of call is n_vals_wanted (+1 for the function)
575                   -> True
576
577                   | otherwise
578                   -> some_benefit && small_enough
579
580                   where
581                     some_benefit = or arg_infos || really_interesting_cont || 
582                                    (not is_top && (once || (n_vals_wanted > 0 && enough_args)))
583                         -- If it occurs more than once, there must be something interesting 
584                         -- about some argument, or the result context, to make it worth inlining
585                         --
586                         -- If a function has a nested defn we also record some-benefit,
587                         -- on the grounds that we are often able to eliminate the binding,
588                         -- and hence the allocation, for the function altogether; this is good
589                         -- for join points.  But this only makes sense for *functions*;
590                         -- inlining a constructor doesn't help allocation unless the result is
591                         -- scrutinised.  UNLESS the constructor occurs just once, albeit possibly
592                         -- in multiple case branches.  Then inlining it doesn't increase allocation,
593                         -- but it does increase the chance that the constructor won't be allocated at all
594                         -- in the branches that don't use it.
595             
596                     enough_args           = n_val_args >= n_vals_wanted
597                     really_interesting_cont | n_val_args <  n_vals_wanted = False       -- Too few args
598                                             | n_val_args == n_vals_wanted = interesting_cont
599                                             | otherwise                   = True        -- Extra args
600                         -- really_interesting_cont tells if the result of the
601                         -- call is in an interesting context.
602
603                     small_enough = (size - discount) <= opt_UF_UseThreshold
604                     discount     = computeDiscount n_vals_wanted arg_discounts res_discount 
605                                                  arg_infos really_interesting_cont
606                 
607     in    
608 #ifdef DEBUG
609     if opt_D_dump_inlinings then
610         pprTrace "Considering inlining"
611                  (ppr id <+> vcat [text "black listed" <+> ppr black_listed,
612                                    text "occ info:" <+> ppr occ,
613                                    text "arg infos" <+> ppr arg_infos,
614                                    text "interesting continuation" <+> ppr interesting_cont,
615                                    text "is value:" <+> ppr is_value,
616                                    text "is cheap:" <+> ppr is_cheap,
617                                    text "is bottom:" <+> ppr is_bot,
618                                    text "is top-level:"    <+> ppr is_top,
619                                    text "guidance" <+> ppr guidance,
620                                    text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO",
621                                    if yes_or_no then
622                                         text "Unfolding =" <+> pprCoreExpr unf_template
623                                    else empty])
624                   result
625     else
626 #endif
627     result
628     }
629
630 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Bool -> Int
631 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos result_used
632         -- We multiple the raw discounts (args_discount and result_discount)
633         -- ty opt_UnfoldingKeenessFactor because the former have to do with
634         -- *size* whereas the discounts imply that there's some extra 
635         -- *efficiency* to be gained (e.g. beta reductions, case reductions) 
636         -- by inlining.
637
638         -- we also discount 1 for each argument passed, because these will
639         -- reduce with the lambdas in the function (we count 1 for a lambda
640         -- in size_up).
641   = 1 +                 -- Discount of 1 because the result replaces the call
642                         -- so we count 1 for the function itself
643     length (take n_vals_wanted arg_infos) +
644                         -- Discount of 1 for each arg supplied, because the 
645                         -- result replaces the call
646     round (opt_UF_KeenessFactor * 
647            fromInt (arg_discount + result_discount))
648   where
649     arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
650
651     mk_arg_discount discount is_evald | is_evald  = discount
652                                       | otherwise = 0
653
654         -- Don't give a result discount unless there are enough args
655     result_discount | result_used = res_discount        -- Over-applied, or case scrut
656                     | otherwise   = 0
657 \end{code}
658
659
660 %************************************************************************
661 %*                                                                      *
662 \subsection{Black-listing}
663 %*                                                                      *
664 %************************************************************************
665
666 Inlining is controlled by the "Inline phase" number, which is set
667 by the per-simplification-pass '-finline-phase' flag.
668
669 For optimisation we use phase 1,2 and nothing (i.e. no -finline-phase flag)
670 in that order.  The meanings of these are determined by the @blackListed@ function
671 here.
672
673 The final simplification doesn't have a phase number.
674
675 Pragmas
676 ~~~~~~~
677         Pragma          Black list if
678
679 (least black listing, most inlining)
680         INLINE n foo    phase is Just p *and* p<n *and* foo appears on LHS of rule
681         INLINE foo      phase is Just p *and*           foo appears on LHS of rule
682         NOINLINE n foo  phase is Just p *and* (p<n *or* foo appears on LHS of rule)
683         NOINLINE foo    always
684 (most black listing, least inlining)
685
686 \begin{code}
687 blackListed :: IdSet            -- Used in transformation rules
688             -> Maybe Int        -- Inline phase
689             -> Id -> Bool       -- True <=> blacklisted
690         
691 -- The blackListed function sees whether a variable should *not* be 
692 -- inlined because of the inline phase we are in.  This is the sole
693 -- place that the inline phase number is looked at.
694
695 blackListed rule_vars Nothing           -- Last phase
696   = \v -> isNeverInlinePrag (idInlinePragma v)
697
698 blackListed rule_vars (Just phase)
699   = \v -> normal_case rule_vars phase v
700
701 normal_case rule_vars phase v 
702   = case idInlinePragma v of
703         NoInlinePragInfo -> has_rules
704
705         IMustNotBeINLINEd from_INLINE Nothing
706           | from_INLINE -> has_rules    -- Black list until final phase
707           | otherwise   -> True         -- Always blacklisted
708
709         IMustNotBeINLINEd from_inline (Just threshold)
710           | from_inline -> (phase < threshold && has_rules)
711           | otherwise   -> (phase < threshold || has_rules)
712   where
713     has_rules =  v `elemVarSet` rule_vars
714               || not (isEmptyCoreRules (idSpecialisation v))
715 \end{code}
716
717
718 SLPJ 95/04: Why @runST@ must be inlined very late:
719 \begin{verbatim}
720 f x =
721   runST ( \ s -> let
722                     (a, s')  = newArray# 100 [] s
723                     (_, s'') = fill_in_array_or_something a x s'
724                   in
725                   freezeArray# a s'' )
726 \end{verbatim}
727 If we inline @runST@, we'll get:
728 \begin{verbatim}
729 f x = let
730         (a, s')  = newArray# 100 [] realWorld#{-NB-}
731         (_, s'') = fill_in_array_or_something a x s'
732       in
733       freezeArray# a s''
734 \end{verbatim}
735 And now the @newArray#@ binding can be floated to become a CAF, which
736 is totally and utterly wrong:
737 \begin{verbatim}
738 f = let
739     (a, s')  = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
740     in
741     \ x ->
742         let (_, s'') = fill_in_array_or_something a x s' in
743         freezeArray# a s''
744 \end{verbatim}
745 All calls to @f@ will share a {\em single} array!  
746
747 Yet we do want to inline runST sometime, so we can avoid
748 needless code.  Solution: black list it until the last moment.
749