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