2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[CoreUnfold]{Core-syntax unfoldings}
6 Unfoldings (which can travel across module boundaries) are in Core
7 syntax (namely @CoreExpr@s).
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.
17 Unfolding, UnfoldingGuidance, -- types
19 noUnfolding, mkTopUnfolding, mkUnfolding, mkCompulsoryUnfolding, seqUnfolding,
20 mkOtherCon, otherCons,
21 unfoldingTemplate, maybeUnfoldingTemplate,
22 isEvaldUnfolding, isCheapUnfolding,
23 hasUnfolding, hasSomeUnfolding,
25 couldBeSmallEnoughToInline,
26 certainlySmallEnoughToInline,
29 calcUnfoldingGuidance,
31 callSiteInline, blackListed
34 #include "HsVersions.h"
36 import CmdLineOpts ( opt_UF_CreationThreshold,
38 opt_UF_ScrutConDiscount,
39 opt_UF_FunAppDiscount,
40 opt_UF_PrimArgDiscount,
42 opt_UF_CheapOp, opt_UF_DearOp, opt_UF_NoRepLit,
43 opt_UnfoldCasms, opt_PprStyle_Debug,
47 import PprCore ( pprCoreExpr )
48 import OccurAnal ( occurAnalyseGlobalExpr )
50 import CoreUtils ( coreExprType, exprIsTrivial, exprIsValue, exprIsCheap )
51 import Id ( Id, idType, idUnique, isId, getIdWorkerInfo,
52 getIdSpecialisation, getInlinePragma, getIdUnfolding,
56 import Name ( isLocallyDefined )
57 import Const ( Con(..), isLitLitLit, isWHNFCon )
58 import PrimOp ( PrimOp(..), primOpIsDupable )
59 import IdInfo ( ArityInfo(..), InlinePragInfo(..), OccInfo(..), insideLam, workerExists )
60 import TyCon ( tyConFamilySize )
61 import Type ( splitAlgTyConApp_maybe, splitFunTy_maybe, isUnLiftedType )
62 import Const ( isNoRepLit )
63 import Unique ( Unique, buildIdKey, augmentIdKey )
64 import Maybes ( maybeToBool )
66 import Util ( isIn, lengthExceeds )
69 #if __GLASGOW_HASKELL__ >= 404
70 import GlaExts ( fromInt )
74 %************************************************************************
76 \subsection{@Unfolding@ and @UnfoldingGuidance@ types}
78 %************************************************************************
84 | OtherCon [Con] -- It ain't one of these
85 -- (OtherCon xs) also indicates that something has been evaluated
86 -- and hence there's no point in re-evaluating it.
87 -- OtherCon [] is used even for non-data-type values
88 -- to indicated evaluated-ness. Notably:
89 -- data C = C !(Int -> Int)
90 -- case x of { C f -> ... }
91 -- Here, f gets an OtherCon [] unfolding.
93 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
94 -- so you'd better unfold.
96 | CoreUnfolding -- An unfolding with redundant cached information
97 CoreExpr -- Template; binder-info is correct
98 Bool -- This is a top-level binding
99 Bool -- exprIsCheap template (cached); it won't duplicate (much) work
100 -- if you inline this in more than one place
101 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
103 UnfoldingGuidance -- Tells about the *size* of the template.
105 seqUnfolding :: Unfolding -> ()
106 seqUnfolding (CoreUnfolding e top b1 b2 g)
107 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
108 seqUnfolding other = ()
112 noUnfolding = NoUnfolding
113 mkOtherCon = OtherCon
115 mkTopUnfolding expr = mkUnfolding True expr
117 mkUnfolding top_lvl expr
118 = CoreUnfolding (occurAnalyseGlobalExpr expr)
122 (calcUnfoldingGuidance opt_UF_CreationThreshold expr)
124 mkCompulsoryUnfolding expr -- Used for things that absolutely must be unfolded
125 = CompulsoryUnfolding (occurAnalyseGlobalExpr expr)
127 unfoldingTemplate :: Unfolding -> CoreExpr
128 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
129 unfoldingTemplate (CompulsoryUnfolding expr) = expr
130 unfoldingTemplate other = panic "getUnfoldingTemplate"
132 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
133 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
134 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
135 maybeUnfoldingTemplate other = Nothing
137 otherCons (OtherCon cons) = cons
140 isEvaldUnfolding :: Unfolding -> Bool
141 isEvaldUnfolding (OtherCon _) = True
142 isEvaldUnfolding (CoreUnfolding _ _ _ is_evald _) = is_evald
143 isEvaldUnfolding other = False
145 isCheapUnfolding :: Unfolding -> Bool
146 isCheapUnfolding (CoreUnfolding _ _ is_cheap _ _) = is_cheap
147 isCheapUnfolding other = False
149 hasUnfolding :: Unfolding -> Bool
150 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
151 hasUnfolding (CompulsoryUnfolding _) = True
152 hasUnfolding other = False
154 hasSomeUnfolding :: Unfolding -> Bool
155 hasSomeUnfolding NoUnfolding = False
156 hasSomeUnfolding other = True
158 data UnfoldingGuidance
160 | UnfoldIfGoodArgs Int -- and "n" value args
162 [Int] -- Discount if the argument is evaluated.
163 -- (i.e., a simplification will definitely
164 -- be possible). One elt of the list per *value* arg.
166 Int -- The "size" of the unfolding; to be elaborated
169 Int -- Scrutinee discount: the discount to substract if the thing is in
170 -- a context (case (thing args) of ...),
171 -- (where there are the right number of arguments.)
173 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
174 seqGuidance other = ()
178 instance Outputable UnfoldingGuidance where
179 ppr UnfoldNever = ptext SLIT("NEVER")
180 ppr (UnfoldIfGoodArgs v cs size discount)
181 = hsep [ ptext SLIT("IF_ARGS"), int v,
182 brackets (hsep (map int cs)),
188 %************************************************************************
190 \subsection[calcUnfoldingGuidance]{Calculate ``unfolding guidance'' for an expression}
192 %************************************************************************
195 calcUnfoldingGuidance
196 :: Int -- bomb out if size gets bigger than this
197 -> CoreExpr -- expression to look at
199 calcUnfoldingGuidance bOMB_OUT_SIZE expr
200 = case collect_val_bndrs expr of { (inline, val_binders, body) ->
202 n_val_binders = length val_binders
204 case (sizeExpr bOMB_OUT_SIZE val_binders body) of
207 | not inline -> UnfoldNever
208 -- A big function with an INLINE pragma must
209 -- have an UnfoldIfGoodArgs guidance
210 | inline -> UnfoldIfGoodArgs n_val_binders
211 (map (const 0) val_binders)
212 (n_val_binders + 2) 0
213 -- See comments with final_size below
215 SizeIs size cased_args scrut_discount
218 (map discount_for val_binders)
224 final_size | inline = 0 -- Trying very agresssive inlining of INLINE things.
225 -- Reason: we don't want to call the un-inlined version,
226 -- because its body is awful
227 -- boxed_size `min` (n_val_binders + 2) -- Trying "+2" again...
228 | otherwise = boxed_size
229 -- The idea is that if there is an INLINE pragma (inline is True)
230 -- and there's a big body, we give a size of n_val_binders+1. This
231 -- This is enough to pass the no-size-increase test in callSiteInline,
233 -- I tried n_val_binders+2, to just defeat the test, on the grounds that
234 -- we don't want to inline an INLINE thing into a totally boring context,
235 -- but I found that some wrappers (notably one for a join point) weren't
236 -- getting inlined, and that was terrible. In that particular case, the
237 -- call site applied the wrapper to realWorld#, so if we made that an
238 -- "interesting" value the inlining would have happened... but it was
239 -- simpler to inline wrappers a little more eagerly instead.
241 -- Sometimes, though, an INLINE thing is smaller than n_val_binders+2.
242 -- A particular case in point is a constructor, which has size 1.
243 -- We want to inline this regardless, hence the `min`
247 | is_fun_ty = num_cases * opt_UF_FunAppDiscount
248 | is_data_ty = num_cases * opt_UF_ScrutConDiscount
249 | otherwise = num_cases * opt_UF_PrimArgDiscount
251 num_cases = foldlBag (\n b' -> if b==b' then n+1 else n) 0 cased_args
252 -- Count occurrences of b in cased_args
254 is_fun_ty = maybeToBool (splitFunTy_maybe arg_ty)
255 (is_data_ty, tycon) = case (splitAlgTyConApp_maybe (idType b)) of
256 Nothing -> (False, panic "discount")
257 Just (tc,_,_) -> (True, tc)
261 collect_val_bndrs e = go False [] e
262 -- We need to be a bit careful about how we collect the
263 -- value binders. In ptic, if we see
264 -- __inline_me (\x y -> e)
265 -- We want to say "2 value binders". Why? So that
266 -- we take account of information given for the arguments
268 go inline rev_vbs (Note InlineMe e) = go True rev_vbs e
269 go inline rev_vbs (Lam b e) | isId b = go inline (b:rev_vbs) e
270 | otherwise = go inline rev_vbs e
271 go inline rev_vbs e = (inline, reverse rev_vbs, e)
275 sizeExpr :: Int -- Bomb out if it gets bigger than this
276 -> [Id] -- Arguments; we're interested in which of these
281 sizeExpr (I# bOMB_OUT_SIZE) top_args expr
284 size_up (Type t) = sizeZero -- Types cost nothing
285 size_up (Var v) = sizeOne
287 size_up (Note _ body) = size_up body -- Notes cost nothing
289 size_up (App fun (Type t)) = size_up fun
290 size_up (App fun arg) = size_up_app fun [arg]
292 size_up (Con con args) = foldr (addSize . nukeScrutDiscount . size_up)
293 (size_up_con con args)
296 size_up (Lam b e) | isId b = size_up e `addSizeN` 1
297 | otherwise = size_up e
299 size_up (Let (NonRec binder rhs) body)
300 = nukeScrutDiscount (size_up rhs) `addSize`
301 size_up body `addSizeN`
302 (if isUnLiftedType (idType binder) then 0 else 1)
303 -- For the allocation
304 -- If the binder has an unlifted type there is no allocation
306 size_up (Let (Rec pairs) body)
307 = nukeScrutDiscount rhs_size `addSize`
308 size_up body `addSizeN`
309 length pairs -- For the allocation
311 rhs_size = foldr (addSize . size_up . snd) sizeZero pairs
313 size_up (Case scrut _ alts)
314 = nukeScrutDiscount (size_up scrut) `addSize`
315 arg_discount scrut `addSize`
316 foldr (addSize . size_up_alt) sizeZero alts
317 `addSizeN` 1 -- charge one for the case itself.
319 -- Just charge for the alts that exist, not the ones that might exist
321 -- case (splitAlgTyConApp_maybe (coreExprType scrut)) of
323 -- Just (tc,_,_) -> tyConFamilySize tc
326 size_up_app (App fun arg) args = size_up_app fun (arg:args)
327 size_up_app fun args = foldr (addSize . nukeScrutDiscount . size_up)
328 (size_up_fun fun args)
331 -- A function application with at least one value argument
332 -- so if the function is an argument give it an arg-discount
333 -- Also behave specially if the function is a build
334 -- Also if the function is a constant Id (constr or primop)
335 -- compute discounts as if it were actually a Con; in the early
336 -- stages these constructors and primops may not yet be inlined
337 size_up_fun (Var fun) args | idUnique fun == buildIdKey = buildSize
338 | idUnique fun == augmentIdKey = augmentSize
339 | fun `is_elem` top_args = scrutArg fun `addSize` fun_size
340 | otherwise = fun_size
342 fun_size = case isConstantId_maybe fun of
343 Just con -> size_up_con con args
346 size_up_fun other args = size_up other
349 size_up_alt (con, bndrs, rhs) = size_up rhs
350 -- Don't charge for args, so that wrappers look cheap
353 size_up_con (Literal lit) args | isNoRepLit lit = sizeN opt_UF_NoRepLit
354 | otherwise = sizeOne
356 size_up_con (DataCon dc) args = conSizeN (valArgCount args)
358 size_up_con (PrimOp op) args = foldr addSize (sizeN op_cost) (map arg_discount args)
359 -- Give an arg-discount if a primop is applies to
360 -- one of the function's arguments
362 op_cost | primOpIsDupable op = opt_UF_CheapOp
363 | otherwise = opt_UF_DearOp
365 -- We want to record if we're case'ing, or applying, an argument
366 arg_discount (Var v) | v `is_elem` top_args = scrutArg v
367 arg_discount other = sizeZero
370 is_elem :: Id -> [Id] -> Bool
371 is_elem = isIn "size_up_scrut"
374 -- These addSize things have to be here because
375 -- I don't want to give them bOMB_OUT_SIZE as an argument
377 addSizeN TooBig _ = TooBig
378 addSizeN (SizeIs n xs d) (I# m)
379 | n_tot -# d <# bOMB_OUT_SIZE = SizeIs n_tot xs d
384 addSize TooBig _ = TooBig
385 addSize _ TooBig = TooBig
386 addSize (SizeIs n1 xs d1) (SizeIs n2 ys d2)
387 | (n_tot -# d_tot) <# bOMB_OUT_SIZE = SizeIs n_tot xys d_tot
392 xys = xs `unionBags` ys
395 Code for manipulating sizes
399 data ExprSize = TooBig
400 | SizeIs Int# -- Size found
401 (Bag Id) -- Arguments cased herein
402 Int# -- Size to subtract if result is scrutinised
403 -- by a case expression
405 sizeZero = SizeIs 0# emptyBag 0#
406 sizeOne = SizeIs 1# emptyBag 0#
407 sizeTwo = SizeIs 2# emptyBag 0#
408 sizeN (I# n) = SizeIs n emptyBag 0#
409 conSizeN (I# n) = SizeIs 1# emptyBag (n +# 1#)
410 -- Treat constructors as size 1, that unfoldAlways responsds 'False'
411 -- when asked about 'x' when x is bound to (C 3#).
412 -- This avoids gratuitous 'ticks' when x itself appears as an
413 -- atomic constructor argument.
415 buildSize = SizeIs (-2#) emptyBag 4#
416 -- We really want to inline applications of build
417 -- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
418 -- Indeed, we should add a result_discount becuause build is
419 -- very like a constructor. We don't bother to check that the
420 -- build is saturated (it usually is). The "-2" discounts for the \c n,
421 -- The "4" is rather arbitrary.
423 augmentSize = SizeIs (-2#) emptyBag 4#
424 -- Ditto (augment t (\cn -> e) ys) should cost only the cost of
425 -- e plus ys. The -2 accounts for the \cn
427 scrutArg v = SizeIs 0# (unitBag v) 0#
429 nukeScrutDiscount (SizeIs n vs d) = SizeIs n vs 0#
430 nukeScrutDiscount TooBig = TooBig
434 %************************************************************************
436 \subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
438 %************************************************************************
440 We have very limited information about an unfolding expression: (1)~so
441 many type arguments and so many value arguments expected---for our
442 purposes here, we assume we've got those. (2)~A ``size'' or ``cost,''
443 a single integer. (3)~An ``argument info'' vector. For this, what we
444 have at the moment is a Boolean per argument position that says, ``I
445 will look with great favour on an explicit constructor in this
446 position.'' (4)~The ``discount'' to subtract if the expression
447 is being scrutinised.
449 Assuming we have enough type- and value arguments (if not, we give up
450 immediately), then we see if the ``discounted size'' is below some
451 (semi-arbitrary) threshold. It works like this: for every argument
452 position where we're looking for a constructor AND WE HAVE ONE in our
453 hands, we get a (again, semi-arbitrary) discount [proportion to the
454 number of constructors in the type being scrutinized].
456 If we're in the context of a scrutinee ( \tr{(case <expr > of A .. -> ...;.. )})
457 and the expression in question will evaluate to a constructor, we use
458 the computed discount size *for the result only* rather than
459 computing the argument discounts. Since we know the result of
460 the expression is going to be taken apart, discounting its size
461 is more accurate (see @sizeExpr@ above for how this discount size
464 We use this one to avoid exporting inlinings that we ``couldn't possibly
465 use'' on the other side. Can be overridden w/ flaggery.
466 Just the same as smallEnoughToInline, except that it has no actual arguments.
469 couldBeSmallEnoughToInline :: UnfoldingGuidance -> Bool
470 couldBeSmallEnoughToInline UnfoldNever = False
471 couldBeSmallEnoughToInline other = True
473 certainlySmallEnoughToInline :: UnfoldingGuidance -> Bool
474 certainlySmallEnoughToInline UnfoldNever = False
475 certainlySmallEnoughToInline (UnfoldIfGoodArgs _ _ size _) = size <= opt_UF_UseThreshold
478 @okToUnfoldInHifile@ is used when emitting unfolding info into an interface
479 file to determine whether an unfolding candidate really should be unfolded.
480 The predicate is needed to prevent @_casm_@s (+ lit-lits) from being emitted
481 into interface files.
483 The reason for inlining expressions containing _casm_s into interface files
484 is that these fragments of C are likely to mention functions/#defines that
485 will be out-of-scope when inlined into another module. This is not an
486 unfixable problem for the user (just need to -#include the approp. header
487 file), but turning it off seems to the simplest thing to do.
490 okToUnfoldInHiFile :: CoreExpr -> Bool
491 okToUnfoldInHiFile e = opt_UnfoldCasms || go e
493 -- Race over an expression looking for CCalls..
495 go (Con (Literal lit) _) = not (isLitLitLit lit)
496 go (Con (PrimOp op) args) = okToUnfoldPrimOp op && all go args
497 go (Con con args) = True -- con args are always atomic
498 go (App fun arg) = go fun && go arg
499 go (Lam _ body) = go body
500 go (Let binds body) = and (map go (body :rhssOfBind binds))
501 go (Case scrut bndr alts) = and (map go (scrut:rhssOfAlts alts))
502 go (Note _ body) = go body
505 -- ok to unfold a PrimOp as long as it's not a _casm_
506 okToUnfoldPrimOp (CCallOp _ is_casm _ _) = not is_casm
507 okToUnfoldPrimOp _ = True
511 %************************************************************************
513 \subsection{callSiteInline}
515 %************************************************************************
517 This is the key function. It decides whether to inline a variable at a call site
519 callSiteInline is used at call sites, so it is a bit more generous.
520 It's a very important function that embodies lots of heuristics.
521 A non-WHNF can be inlined if it doesn't occur inside a lambda,
522 and occurs exactly once or
523 occurs once in each branch of a case and is small
525 If the thing is in WHNF, there's no danger of duplicating work,
526 so we can inline if it occurs once, or is small
529 callSiteInline :: Bool -- True <=> the Id is black listed
530 -> Bool -- 'inline' note at call site
533 -> [Bool] -- One for each value arg; True if it is interesting
534 -> Bool -- True <=> continuation is interesting
535 -> Maybe CoreExpr -- Unfolding, if any
538 callSiteInline black_listed inline_call occ id arg_infos interesting_cont
539 = case getIdUnfolding id of {
540 NoUnfolding -> Nothing ;
541 OtherCon _ -> Nothing ;
542 CompulsoryUnfolding unf_template | black_listed -> Nothing
543 | otherwise -> Just unf_template ;
544 -- Primops have compulsory unfoldings, but
545 -- may have rules, in which case they are
546 -- black listed till later
547 CoreUnfolding unf_template is_top is_cheap _ guidance ->
550 result | yes_or_no = Just unf_template
551 | otherwise = Nothing
553 n_val_args = length arg_infos
556 | black_listed = False
557 | otherwise = case occ of
558 IAmDead -> pprTrace "callSiteInline: dead" (ppr id) False
559 IAmALoopBreaker -> False
560 OneOcc in_lam one_br -> (not in_lam || is_cheap) && consider_safe in_lam True one_br
561 NoOccInfo -> is_cheap && consider_safe True False False
563 consider_safe in_lam once once_in_one_branch
564 -- consider_safe decides whether it's a good idea to inline something,
565 -- given that there's no work-duplication issue (the caller checks that).
566 -- once_in_one_branch = True means there's a unique textual occurrence
569 | once_in_one_branch -- Be very keen to inline something if this is its unique occurrence; that
570 -- gives a good chance of eliminating the original binding for the thing.
571 -- The only time we hold back is when substituting inside a lambda;
572 -- then if the context is totally uninteresting (not applied, not scrutinised)
573 -- there is no point in substituting because it might just increase allocation.
574 = not in_lam || not (null arg_infos) || interesting_cont
578 UnfoldNever -> False ;
579 UnfoldIfGoodArgs n_vals_wanted arg_discounts size res_discount
581 | enough_args && size <= (n_vals_wanted + 1)
583 -- Size of call is n_vals_wanted (+1 for the function)
587 -> some_benefit && small_enough
590 some_benefit = or arg_infos || really_interesting_cont ||
591 (not is_top && (once || (n_vals_wanted > 0 && enough_args)))
592 -- If it occurs more than once, there must be something interesting
593 -- about some argument, or the result context, to make it worth inlining
595 -- If a function has a nested defn we also record some-benefit,
596 -- on the grounds that we are often able to eliminate the binding,
597 -- and hence the allocation, for the function altogether; this is good
598 -- for join points. But this only makes sense for *functions*;
599 -- inlining a constructor doesn't help allocation unless the result is
600 -- scrutinised. UNLESS the constructor occurs just once, albeit possibly
601 -- in multiple case branches. Then inlining it doesn't increase allocation,
602 -- but it does increase the chance that the constructor won't be allocated at all
603 -- in the branches that don't use it.
605 enough_args = n_val_args >= n_vals_wanted
606 really_interesting_cont | n_val_args < n_vals_wanted = False -- Too few args
607 | n_val_args == n_vals_wanted = interesting_cont
608 | otherwise = True -- Extra args
609 -- really_interesting_cont tells if the result of the
610 -- call is in an interesting context.
612 small_enough = (size - discount) <= opt_UF_UseThreshold
613 discount = computeDiscount n_vals_wanted arg_discounts res_discount
614 arg_infos really_interesting_cont
618 if opt_D_dump_inlinings then
619 pprTrace "Considering inlining"
620 (ppr id <+> vcat [text "black listed" <+> ppr black_listed,
621 text "occ info:" <+> ppr occ,
622 text "arg infos" <+> ppr arg_infos,
623 text "interesting continuation" <+> ppr interesting_cont,
624 text "is cheap" <+> ppr is_cheap,
625 text "guidance" <+> ppr guidance,
626 text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO",
628 text "Unfolding =" <+> pprCoreExpr unf_template
636 computeDiscount :: Int -> [Int] -> Int -> [Bool] -> Bool -> Int
637 computeDiscount n_vals_wanted arg_discounts res_discount arg_infos result_used
638 -- We multiple the raw discounts (args_discount and result_discount)
639 -- ty opt_UnfoldingKeenessFactor because the former have to do with
640 -- *size* whereas the discounts imply that there's some extra
641 -- *efficiency* to be gained (e.g. beta reductions, case reductions)
644 -- we also discount 1 for each argument passed, because these will
645 -- reduce with the lambdas in the function (we count 1 for a lambda
647 = 1 + -- Discount of 1 because the result replaces the call
648 -- so we count 1 for the function itself
649 length (take n_vals_wanted arg_infos) +
650 -- Discount of 1 for each arg supplied, because the
651 -- result replaces the call
652 round (opt_UF_KeenessFactor *
653 fromInt (arg_discount + result_discount))
655 arg_discount = sum (zipWith mk_arg_discount arg_discounts arg_infos)
657 mk_arg_discount discount is_evald | is_evald = discount
660 -- Don't give a result discount unless there are enough args
661 result_discount | result_used = res_discount -- Over-applied, or case scrut
666 %************************************************************************
668 \subsection{Black-listing}
670 %************************************************************************
672 Inlining is controlled by the "Inline phase" number, which is set
673 by the per-simplification-pass '-finline-phase' flag.
675 For optimisation we use phase 1,2 and nothing (i.e. no -finline-phase flag)
676 in that order. The meanings of these are determined by the @blackListed@ function
679 The final simplification doesn't have a phase number
685 (least black listing, most inlining)
686 INLINE n foo phase is Just p *and* p<n *and* foo appears on LHS of rule
687 INLINE foo phase is Just p *and* foo appears on LHS of rule
688 NOINLINE n foo phase is Just p *and* (p<n *or* foo appears on LHS of rule)
690 (most black listing, least inlining)
693 blackListed :: IdSet -- Used in transformation rules
694 -> Maybe Int -- Inline phase
695 -> Id -> Bool -- True <=> blacklisted
697 -- The blackListed function sees whether a variable should *not* be
698 -- inlined because of the inline phase we are in. This is the sole
699 -- place that the inline phase number is looked at.
701 blackListed rule_vars Nothing -- Last phase
702 = \v -> case getInlinePragma v of
703 IMustNotBeINLINEd False Nothing -> True -- An unconditional NOINLINE pragma
706 blackListed rule_vars (Just 0)
707 -- Phase 0: used for 'no imported inlinings please'
708 -- This prevents wrappers getting inlined which in turn is bad for full laziness
709 -- NEW: try using 'not a wrapper' rather than 'not imported' in this phase.
710 -- This allows a little more inlining, which seems to be important, sometimes.
711 -- For example PrelArr.newIntArr gets better.
712 = \v -> -- workerExists (getIdWorkerInfo v) || normal_case rule_vars 0 v
713 -- True -- Try going back to no inlinings at all
714 -- BUT: I found that there is some advantage in doing
715 -- local inlinings first. For example in fish/Main.hs
716 -- it's advantageous to inline scale_vec2 before inlining
717 -- wrappers from PrelNum that make it look big.
718 not (isLocallyDefined v) || normal_case rule_vars 0 v -- This seems best at the moment
720 blackListed rule_vars (Just phase)
721 = \v -> normal_case rule_vars phase v
723 normal_case rule_vars phase v
724 = case getInlinePragma v of
725 NoInlinePragInfo -> has_rules
727 IMustNotBeINLINEd from_INLINE Nothing
728 | from_INLINE -> has_rules -- Black list until final phase
729 | otherwise -> True -- Always blacklisted
731 IMustNotBeINLINEd from_inline (Just threshold)
732 | from_inline -> phase < threshold && has_rules
733 | otherwise -> phase < threshold || has_rules
735 has_rules = v `elemVarSet` rule_vars
736 || not (isEmptyCoreRules (getIdSpecialisation v))
740 SLPJ 95/04: Why @runST@ must be inlined very late:
744 (a, s') = newArray# 100 [] s
745 (_, s'') = fill_in_array_or_something a x s'
749 If we inline @runST@, we'll get:
752 (a, s') = newArray# 100 [] realWorld#{-NB-}
753 (_, s'') = fill_in_array_or_something a x s'
757 And now the @newArray#@ binding can be floated to become a CAF, which
758 is totally and utterly wrong:
761 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
764 let (_, s'') = fill_in_array_or_something a x s' in
767 All calls to @f@ will share a {\em single} array!
769 Yet we do want to inline runST sometime, so we can avoid
770 needless code. Solution: black list it until the last moment.