Multiple improvements to CPS algorithm.
[ghc-hetmet.git] / compiler / codeGen / ClosureInfo.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The Univserity of Glasgow 1992-2004
4 %
5
6         Data structures which describe closures, and
7         operations over those data structures
8
9                 Nothing monadic in here
10
11 Much of the rationale for these things is in the ``details'' part of
12 the STG paper.
13
14 \begin{code}
15 module ClosureInfo (
16         ClosureInfo(..), LambdaFormInfo(..),    -- would be abstract but
17         StandardFormInfo(..),                   -- mkCmmInfo looks inside
18         SMRep,
19
20         ArgDescr(..), Liveness(..), 
21         C_SRT(..), needsSRT,
22
23         mkLFThunk, mkLFReEntrant, mkConLFInfo, mkSelectorLFInfo,
24         mkApLFInfo, mkLFImported, mkLFArgument, mkLFLetNoEscape,
25
26         mkClosureInfo, mkConInfo,
27
28         closureSize, closureNonHdrSize,
29         closureGoodStuffSize, closurePtrsSize,
30         slopSize, 
31
32         closureName, infoTableLabelFromCI,
33         closureLabelFromCI, closureSRT,
34         closureLFInfo, isLFThunk,closureSMRep, closureUpdReqd, 
35         closureNeedsUpdSpace, closureIsThunk,
36         closureSingleEntry, closureReEntrant, isConstrClosure_maybe,
37         closureFunInfo, isStandardFormThunk, isKnownFun,
38
39         enterIdLabel, enterLocalIdLabel, enterReturnPtLabel,
40
41         nodeMustPointToIt, 
42         CallMethod(..), getCallMethod,
43
44         blackHoleOnEntry,
45
46         staticClosureRequired,
47         getClosureType,
48
49         isToplevClosure,
50         closureValDescr, closureTypeDescr,      -- profiling
51
52         isStaticClosure,
53         cafBlackHoleClosureInfo, seCafBlackHoleClosureInfo,
54
55         staticClosureNeedsLink,
56     ) where
57
58 #include "../includes/MachDeps.h"
59 #include "HsVersions.h"
60
61 import StgSyn
62 import SMRep
63
64 import CLabel
65
66 import Packages
67 import PackageConfig
68 import StaticFlags
69 import Id
70 import DataCon
71 import Name
72 import OccName
73 import Type
74 import TypeRep
75 import TcType
76 import TyCon
77 import BasicTypes
78 import FastString
79 import Outputable
80 import Constants
81 \end{code}
82
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection[ClosureInfo-datatypes]{Data types for closure information}
87 %*                                                                      *
88 %************************************************************************
89
90 Information about a closure, from the code generator's point of view.
91
92 A ClosureInfo decribes the info pointer of a closure.  It has
93 enough information 
94   a) to construct the info table itself
95   b) to allocate a closure containing that info pointer (i.e.
96         it knows the info table label)
97
98 We make a ClosureInfo for
99         - each let binding (both top level and not)
100         - each data constructor (for its shared static and
101                 dynamic info tables)
102
103 \begin{code}
104 data ClosureInfo
105   = ClosureInfo {
106         closureName   :: !Name,           -- The thing bound to this closure
107         closureLFInfo :: !LambdaFormInfo, -- NOTE: not an LFCon (see below)
108         closureSMRep  :: !SMRep,          -- representation used by storage mgr
109         closureSRT    :: !C_SRT,          -- What SRT applies to this closure
110         closureType   :: !Type,           -- Type of closure (ToDo: remove)
111         closureDescr  :: !String          -- closure description (for profiling)
112     }
113
114   -- Constructor closures don't have a unique info table label (they use
115   -- the constructor's info table), and they don't have an SRT.
116   | ConInfo {
117         closureCon       :: !DataCon,
118         closureSMRep     :: !SMRep,
119         closureDllCon    :: !Bool       -- is in a separate DLL
120     }
121
122 -- C_SRT is what StgSyn.SRT gets translated to... 
123 -- we add a label for the table, and expect only the 'offset/length' form
124
125 data C_SRT = NoC_SRT
126            | C_SRT !CLabel !WordOff !StgHalfWord {-bitmap or escape-}
127            deriving (Eq)
128
129 needsSRT :: C_SRT -> Bool
130 needsSRT NoC_SRT       = False
131 needsSRT (C_SRT _ _ _) = True
132
133 instance Outputable C_SRT where
134   ppr (NoC_SRT) = ptext SLIT("_no_srt_")
135   ppr (C_SRT label off bitmap) = parens (ppr label <> comma <> ppr off <> comma <> text (show bitmap))
136 \end{code}
137
138 %************************************************************************
139 %*                                                                      *
140 \subsubsection[LambdaFormInfo-datatype]{@LambdaFormInfo@: source-derivable info}
141 %*                                                                      *
142 %************************************************************************
143
144 Information about an identifier, from the code generator's point of
145 view.  Every identifier is bound to a LambdaFormInfo in the
146 environment, which gives the code generator enough info to be able to
147 tail call or return that identifier.
148
149 Note that a closure is usually bound to an identifier, so a
150 ClosureInfo contains a LambdaFormInfo.
151
152 \begin{code}
153 data LambdaFormInfo
154   = LFReEntrant         -- Reentrant closure (a function)
155         TopLevelFlag    -- True if top level
156         !Int            -- Arity. Invariant: always > 0
157         !Bool           -- True <=> no fvs
158         ArgDescr        -- Argument descriptor (should reall be in ClosureInfo)
159
160   | LFCon               -- A saturated constructor application
161         DataCon         -- The constructor
162
163   | LFThunk             -- Thunk (zero arity)
164         TopLevelFlag
165         !Bool           -- True <=> no free vars
166         !Bool           -- True <=> updatable (i.e., *not* single-entry)
167         StandardFormInfo
168         !Bool           -- True <=> *might* be a function type
169
170   | LFUnknown           -- Used for function arguments and imported things.
171                         --  We know nothing about  this closure.  Treat like
172                         -- updatable "LFThunk"...
173                         -- Imported things which we do know something about use
174                         -- one of the other LF constructors (eg LFReEntrant for
175                         -- known functions)
176         !Bool           -- True <=> *might* be a function type
177
178   | LFLetNoEscape       -- See LetNoEscape module for precise description of
179                         -- these "lets".
180         !Int            -- arity;
181
182   | LFBlackHole         -- Used for the closures allocated to hold the result
183                         -- of a CAF.  We want the target of the update frame to
184                         -- be in the heap, so we make a black hole to hold it.
185         CLabel          -- Flavour (info label, eg CAF_BLACKHOLE_info).
186
187
188 -------------------------
189 -- An ArgDsecr describes the argument pattern of a function
190
191 data ArgDescr
192   = ArgSpec             -- Fits one of the standard patterns
193         !StgHalfWord    -- RTS type identifier ARG_P, ARG_N, ...
194
195   | ArgGen              -- General case
196         Liveness        -- Details about the arguments
197
198
199 -------------------------
200 -- We represent liveness bitmaps as a Bitmap (whose internal
201 -- representation really is a bitmap).  These are pinned onto case return
202 -- vectors to indicate the state of the stack for the garbage collector.
203 -- 
204 -- In the compiled program, liveness bitmaps that fit inside a single
205 -- word (StgWord) are stored as a single word, while larger bitmaps are
206 -- stored as a pointer to an array of words. 
207
208 data Liveness
209   = SmallLiveness       -- Liveness info that fits in one word
210         StgWord         -- Here's the bitmap
211
212   | BigLiveness         -- Liveness info witha a multi-word bitmap
213         CLabel          -- Label for the bitmap
214
215
216 -------------------------
217 -- StandardFormInfo tells whether this thunk has one of 
218 -- a small number of standard forms
219
220 data StandardFormInfo
221   = NonStandardThunk
222         -- Not of of the standard forms
223
224   | SelectorThunk
225         -- A SelectorThunk is of form
226         --      case x of
227         --             con a1,..,an -> ak
228         -- and the constructor is from a single-constr type.
229        WordOff                  -- 0-origin offset of ak within the "goods" of 
230                         -- constructor (Recall that the a1,...,an may be laid
231                         -- out in the heap in a non-obvious order.)
232
233   | ApThunk 
234         -- An ApThunk is of form
235         --      x1 ... xn
236         -- The code for the thunk just pushes x2..xn on the stack and enters x1.
237         -- There are a few of these (for 1 <= n <= MAX_SPEC_AP_SIZE) pre-compiled
238         -- in the RTS to save space.
239         Int             -- Arity, n
240 \end{code}
241
242 %************************************************************************
243 %*                                                                      *
244 \subsection[ClosureInfo-construction]{Functions which build LFInfos}
245 %*                                                                      *
246 %************************************************************************
247
248 \begin{code}
249 mkLFReEntrant :: TopLevelFlag   -- True of top level
250               -> [Id]           -- Free vars
251               -> [Id]           -- Args
252               -> ArgDescr       -- Argument descriptor
253               -> LambdaFormInfo
254
255 mkLFReEntrant top fvs args arg_descr 
256   = LFReEntrant top (length args) (null fvs) arg_descr
257
258 mkLFThunk thunk_ty top fvs upd_flag
259   = ASSERT( not (isUpdatable upd_flag) || not (isUnLiftedType thunk_ty) )
260     LFThunk top (null fvs) 
261             (isUpdatable upd_flag)
262             NonStandardThunk 
263             (might_be_a_function thunk_ty)
264
265 might_be_a_function :: Type -> Bool
266 -- Return False only if we are *sure* it's a data type
267 -- Look through newtypes etc as much as poss
268 might_be_a_function ty
269   = case splitTyConApp_maybe (repType ty) of
270         Just (tc, _) -> not (isDataTyCon tc)
271         Nothing      -> True
272 \end{code}
273
274 @mkConLFInfo@ is similar, for constructors.
275
276 \begin{code}
277 mkConLFInfo :: DataCon -> LambdaFormInfo
278 mkConLFInfo con = LFCon con
279
280 mkSelectorLFInfo id offset updatable
281   = LFThunk NotTopLevel False updatable (SelectorThunk offset) 
282         (might_be_a_function (idType id))
283
284 mkApLFInfo id upd_flag arity
285   = LFThunk NotTopLevel (arity == 0) (isUpdatable upd_flag) (ApThunk arity)
286         (might_be_a_function (idType id))
287 \end{code}
288
289 Miscellaneous LF-infos.
290
291 \begin{code}
292 mkLFArgument id = LFUnknown (might_be_a_function (idType id))
293
294 mkLFLetNoEscape = LFLetNoEscape
295
296 mkLFImported :: Id -> LambdaFormInfo
297 mkLFImported id
298   = case idArity id of
299       n | n > 0 -> LFReEntrant TopLevel n True (panic "arg_descr")  -- n > 0
300       other -> mkLFArgument id -- Not sure of exact arity
301 \end{code}
302
303 \begin{code}
304 isLFThunk :: LambdaFormInfo -> Bool
305 isLFThunk (LFThunk _ _ _ _ _)  = True
306 isLFThunk (LFBlackHole _)      = True
307         -- return True for a blackhole: this function is used to determine
308         -- whether to use the thunk header in SMP mode, and a blackhole
309         -- must have one.
310 isLFThunk _ = False
311 \end{code}
312
313 %************************************************************************
314 %*                                                                      *
315         Building ClosureInfos
316 %*                                                                      *
317 %************************************************************************
318
319 \begin{code}
320 mkClosureInfo :: Bool           -- Is static
321               -> Id
322               -> LambdaFormInfo 
323               -> Int -> Int     -- Total and pointer words
324               -> C_SRT
325               -> String         -- String descriptor
326               -> ClosureInfo
327 mkClosureInfo is_static id lf_info tot_wds ptr_wds srt_info descr
328   = ClosureInfo { closureName = name, 
329                   closureLFInfo = lf_info,
330                   closureSMRep = sm_rep, 
331                   closureSRT = srt_info,
332                   closureType = idType id,
333                   closureDescr = descr }
334   where
335     name   = idName id
336     sm_rep = chooseSMRep is_static lf_info tot_wds ptr_wds
337
338 mkConInfo :: PackageId
339           -> Bool       -- Is static
340           -> DataCon    
341           -> Int -> Int -- Total and pointer words
342           -> ClosureInfo
343 mkConInfo this_pkg is_static data_con tot_wds ptr_wds
344    = ConInfo {  closureSMRep = sm_rep,
345                 closureCon = data_con,
346                 closureDllCon = isDllName this_pkg (dataConName data_con) }
347   where
348     sm_rep = chooseSMRep is_static (mkConLFInfo data_con) tot_wds ptr_wds
349 \end{code}
350
351 %************************************************************************
352 %*                                                                      *
353 \subsection[ClosureInfo-sizes]{Functions about closure {\em sizes}}
354 %*                                                                      *
355 %************************************************************************
356
357 \begin{code}
358 closureSize :: ClosureInfo -> WordOff
359 closureSize cl_info = hdr_size + closureNonHdrSize cl_info
360   where hdr_size  | closureIsThunk cl_info = thunkHdrSize
361                   | otherwise              = fixedHdrSize
362         -- All thunks use thunkHdrSize, even if they are non-updatable.
363         -- this is because we don't have separate closure types for
364         -- updatable vs. non-updatable thunks, so the GC can't tell the
365         -- difference.  If we ever have significant numbers of non-
366         -- updatable thunks, it might be worth fixing this.
367
368 closureNonHdrSize :: ClosureInfo -> WordOff
369 closureNonHdrSize cl_info
370   = tot_wds + computeSlopSize tot_wds cl_info
371   where
372     tot_wds = closureGoodStuffSize cl_info
373
374 closureGoodStuffSize :: ClosureInfo -> WordOff
375 closureGoodStuffSize cl_info
376   = let (ptrs, nonptrs) = sizes_from_SMRep (closureSMRep cl_info)
377     in  ptrs + nonptrs
378
379 closurePtrsSize :: ClosureInfo -> WordOff
380 closurePtrsSize cl_info
381   = let (ptrs, _) = sizes_from_SMRep (closureSMRep cl_info)
382     in  ptrs
383
384 -- not exported:
385 sizes_from_SMRep :: SMRep -> (WordOff,WordOff)
386 sizes_from_SMRep (GenericRep _ ptrs nonptrs _)   = (ptrs, nonptrs)
387 sizes_from_SMRep BlackHoleRep                    = (0, 0)
388 \end{code}
389
390 Computing slop size.  WARNING: this looks dodgy --- it has deep
391 knowledge of what the storage manager does with the various
392 representations...
393
394 Slop Requirements: every thunk gets an extra padding word in the
395 header, which takes the the updated value.
396
397 \begin{code}
398 slopSize cl_info = computeSlopSize payload_size cl_info
399   where payload_size = closureGoodStuffSize cl_info
400
401 computeSlopSize :: WordOff -> ClosureInfo -> WordOff
402 computeSlopSize payload_size cl_info
403   = max 0 (minPayloadSize smrep updatable - payload_size)
404   where
405         smrep        = closureSMRep cl_info
406         updatable    = closureNeedsUpdSpace cl_info
407
408 -- we leave space for an update if either (a) the closure is updatable
409 -- or (b) it is a static thunk.  This is because a static thunk needs
410 -- a static link field in a predictable place (after the slop), regardless
411 -- of whether it is updatable or not.
412 closureNeedsUpdSpace (ClosureInfo { closureLFInfo = 
413                                         LFThunk TopLevel _ _ _ _ }) = True
414 closureNeedsUpdSpace cl_info = closureUpdReqd cl_info
415
416 minPayloadSize :: SMRep -> Bool -> WordOff
417 minPayloadSize smrep updatable
418   = case smrep of
419         BlackHoleRep                            -> min_upd_size
420         GenericRep _ _ _ _      | updatable     -> min_upd_size
421         GenericRep True _ _ _                   -> 0 -- static
422         GenericRep False _ _ _                  -> mIN_PAYLOAD_SIZE
423           --       ^^^^^___ dynamic
424   where
425    min_upd_size =
426         ASSERT(mIN_PAYLOAD_SIZE <= sIZEOF_StgSMPThunkHeader)
427         0       -- check that we already have enough
428                 -- room for mIN_SIZE_NonUpdHeapObject,
429                 -- due to the extra header word in SMP
430 \end{code}
431
432 %************************************************************************
433 %*                                                                      *
434 \subsection[SMreps]{Choosing SM reps}
435 %*                                                                      *
436 %************************************************************************
437
438 \begin{code}
439 chooseSMRep
440         :: Bool                 -- True <=> static closure
441         -> LambdaFormInfo
442         -> WordOff -> WordOff   -- Tot wds, ptr wds
443         -> SMRep
444
445 chooseSMRep is_static lf_info tot_wds ptr_wds
446   = let
447          nonptr_wds   = tot_wds - ptr_wds
448          closure_type = getClosureType is_static ptr_wds lf_info
449     in
450     GenericRep is_static ptr_wds nonptr_wds closure_type        
451
452 -- We *do* get non-updatable top-level thunks sometimes.  eg. f = g
453 -- gets compiled to a jump to g (if g has non-zero arity), instead of
454 -- messing around with update frames and PAPs.  We set the closure type
455 -- to FUN_STATIC in this case.
456
457 getClosureType :: Bool -> WordOff -> LambdaFormInfo -> ClosureType
458 getClosureType is_static ptr_wds lf_info
459   = case lf_info of
460         LFCon con | is_static && ptr_wds == 0   -> ConstrNoCaf
461                   | otherwise                   -> Constr
462         LFReEntrant _ _ _ _                     -> Fun
463         LFThunk _ _ _ (SelectorThunk _) _       -> ThunkSelector
464         LFThunk _ _ _ _ _                       -> Thunk
465         _ -> panic "getClosureType"
466 \end{code}
467
468 %************************************************************************
469 %*                                                                      *
470 \subsection[ClosureInfo-4-questions]{Four major questions about @ClosureInfo@}
471 %*                                                                      *
472 %************************************************************************
473
474 Be sure to see the stg-details notes about these...
475
476 \begin{code}
477 nodeMustPointToIt :: LambdaFormInfo -> Bool
478 nodeMustPointToIt (LFReEntrant top _ no_fvs _)
479   = not no_fvs ||   -- Certainly if it has fvs we need to point to it
480     isNotTopLevel top
481                     -- If it is not top level we will point to it
482                     --   We can have a \r closure with no_fvs which
483                     --   is not top level as special case cgRhsClosure
484                     --   has been dissabled in favour of let floating
485
486                 -- For lex_profiling we also access the cost centre for a
487                 -- non-inherited function i.e. not top level
488                 -- the  not top  case above ensures this is ok.
489
490 nodeMustPointToIt (LFCon _) = True
491
492         -- Strictly speaking, the above two don't need Node to point
493         -- to it if the arity = 0.  But this is a *really* unlikely
494         -- situation.  If we know it's nil (say) and we are entering
495         -- it. Eg: let x = [] in x then we will certainly have inlined
496         -- x, since nil is a simple atom.  So we gain little by not
497         -- having Node point to known zero-arity things.  On the other
498         -- hand, we do lose something; Patrick's code for figuring out
499         -- when something has been updated but not entered relies on
500         -- having Node point to the result of an update.  SLPJ
501         -- 27/11/92.
502
503 nodeMustPointToIt (LFThunk _ no_fvs updatable NonStandardThunk _)
504   = updatable || not no_fvs || opt_SccProfilingOn
505           -- For the non-updatable (single-entry case):
506           --
507           -- True if has fvs (in which case we need access to them, and we
508           --                should black-hole it)
509           -- or profiling (in which case we need to recover the cost centre
510           --             from inside it)
511
512 nodeMustPointToIt (LFThunk _ no_fvs updatable some_standard_form_thunk _)
513   = True  -- Node must point to any standard-form thunk
514
515 nodeMustPointToIt (LFUnknown _)     = True
516 nodeMustPointToIt (LFBlackHole _)   = True    -- BH entry may require Node to point
517 nodeMustPointToIt (LFLetNoEscape _) = False 
518 \end{code}
519
520 The entry conventions depend on the type of closure being entered,
521 whether or not it has free variables, and whether we're running
522 sequentially or in parallel.
523
524 \begin{tabular}{lllll}
525 Closure Characteristics & Parallel & Node Req'd & Argument Passing & Enter Via \\
526 Unknown                         & no & yes & stack      & node \\
527 Known fun ($\ge$ 1 arg), no fvs         & no & no  & registers  & fast entry (enough args) \\
528 \ & \ & \ & \                                           & slow entry (otherwise) \\
529 Known fun ($\ge$ 1 arg), fvs    & no & yes & registers  & fast entry (enough args) \\
530 0 arg, no fvs @\r,\s@           & no & no  & n/a        & direct entry \\
531 0 arg, no fvs @\u@              & no & yes & n/a        & node \\
532 0 arg, fvs @\r,\s@              & no & yes & n/a        & direct entry \\
533 0 arg, fvs @\u@                 & no & yes & n/a        & node \\
534
535 Unknown                         & yes & yes & stack     & node \\
536 Known fun ($\ge$ 1 arg), no fvs         & yes & no  & registers & fast entry (enough args) \\
537 \ & \ & \ & \                                           & slow entry (otherwise) \\
538 Known fun ($\ge$ 1 arg), fvs    & yes & yes & registers & node \\
539 0 arg, no fvs @\r,\s@           & yes & no  & n/a       & direct entry \\
540 0 arg, no fvs @\u@              & yes & yes & n/a       & node \\
541 0 arg, fvs @\r,\s@              & yes & yes & n/a       & node \\
542 0 arg, fvs @\u@                 & yes & yes & n/a       & node\\
543 \end{tabular}
544
545 When black-holing, single-entry closures could also be entered via node
546 (rather than directly) to catch double-entry.
547
548 \begin{code}
549 data CallMethod
550   = EnterIt                             -- no args, not a function
551
552   | JumpToIt CLabel                     -- no args, not a function, but we
553                                         -- know what its entry code is
554
555   | ReturnIt                            -- it's a function, but we have
556                                         -- zero args to apply to it, so just
557                                         -- return it.
558
559   | ReturnCon DataCon                   -- It's a data constructor, just return it
560
561   | SlowCall                            -- Unknown fun, or known fun with
562                                         -- too few args.
563
564   | DirectEntry                         -- Jump directly, with args in regs
565         CLabel                          --   The code label
566         Int                             --   Its arity
567
568 getCallMethod :: PackageId
569               -> Name           -- Function being applied
570               -> LambdaFormInfo -- Its info
571               -> Int            -- Number of available arguments
572               -> CallMethod
573
574 getCallMethod this_pkg name lf_info n_args
575   | nodeMustPointToIt lf_info && opt_Parallel
576   =     -- If we're parallel, then we must always enter via node.  
577         -- The reason is that the closure may have been         
578         -- fetched since we allocated it.
579     EnterIt
580
581 getCallMethod this_pkg name (LFReEntrant _ arity _ _) n_args
582   | n_args == 0    = ASSERT( arity /= 0 )
583                      ReturnIt   -- No args at all
584   | n_args < arity = SlowCall   -- Not enough args
585   | otherwise      = DirectEntry (enterIdLabel this_pkg name) arity
586
587 getCallMethod this_pkg name (LFCon con) n_args
588   = ASSERT( n_args == 0 )
589     ReturnCon con
590
591 getCallMethod this_pkg name (LFThunk _ _ updatable std_form_info is_fun) n_args
592   | is_fun      -- *Might* be a function, so we must "call" it (which is always safe)
593   = SlowCall    -- We cannot just enter it [in eval/apply, the entry code
594                 -- is the fast-entry code]
595
596   -- Since is_fun is False, we are *definitely* looking at a data value
597   | updatable || opt_DoTickyProfiling  -- to catch double entry
598       {- OLD: || opt_SMP
599          I decided to remove this, because in SMP mode it doesn't matter
600          if we enter the same thunk multiple times, so the optimisation
601          of jumping directly to the entry code is still valid.  --SDM
602         -}
603   = EnterIt
604     -- We used to have ASSERT( n_args == 0 ), but actually it is
605     -- possible for the optimiser to generate
606     --   let bot :: Int = error Int "urk"
607     --   in (bot `cast` unsafeCoerce Int (Int -> Int)) 3
608     -- This happens as a result of the case-of-error transformation
609     -- So the right thing to do is just to enter the thing
610
611   | otherwise   -- Jump direct to code for single-entry thunks
612   = ASSERT( n_args == 0 )
613     JumpToIt (thunkEntryLabel this_pkg name std_form_info updatable)
614
615 getCallMethod this_pkg name (LFUnknown True) n_args
616   = SlowCall -- might be a function
617
618 getCallMethod this_pkg name (LFUnknown False) n_args
619   = ASSERT2 ( n_args == 0, ppr name <+> ppr n_args ) 
620     EnterIt -- Not a function
621
622 getCallMethod this_pkg name (LFBlackHole _) n_args
623   = SlowCall    -- Presumably the black hole has by now
624                 -- been updated, but we don't know with
625                 -- what, so we slow call it
626
627 getCallMethod this_pkg name (LFLetNoEscape 0) n_args
628   = JumpToIt (enterReturnPtLabel (nameUnique name))
629
630 getCallMethod this_pkg name (LFLetNoEscape arity) n_args
631   | n_args == arity = DirectEntry (enterReturnPtLabel (nameUnique name)) arity
632   | otherwise = pprPanic "let-no-escape: " (ppr name <+> ppr arity)
633
634 blackHoleOnEntry :: ClosureInfo -> Bool
635 -- Static closures are never themselves black-holed.
636 -- Updatable ones will be overwritten with a CAFList cell, which points to a 
637 -- black hole;
638 -- Single-entry ones have no fvs to plug, and we trust they don't form part 
639 -- of a loop.
640
641 blackHoleOnEntry ConInfo{} = False
642 blackHoleOnEntry (ClosureInfo { closureLFInfo = lf_info, closureSMRep = rep })
643   | isStaticRep rep
644   = False       -- Never black-hole a static closure
645
646   | otherwise
647   = case lf_info of
648         LFReEntrant _ _ _ _       -> False
649         LFLetNoEscape _           -> False
650         LFThunk _ no_fvs updatable _ _
651           -> if updatable
652              then not opt_OmitBlackHoling
653              else opt_DoTickyProfiling || not no_fvs
654                   -- the former to catch double entry,
655                   -- and the latter to plug space-leaks.  KSW/SDM 1999-04.
656
657         other -> panic "blackHoleOnEntry"       -- Should never happen
658
659 isStandardFormThunk :: LambdaFormInfo -> Bool
660 isStandardFormThunk (LFThunk _ _ _ (SelectorThunk _) _) = True
661 isStandardFormThunk (LFThunk _ _ _ (ApThunk _) _)       = True
662 isStandardFormThunk other_lf_info                       = False
663
664 isKnownFun :: LambdaFormInfo -> Bool
665 isKnownFun (LFReEntrant _ _ _ _) = True
666 isKnownFun (LFLetNoEscape _) = True
667 isKnownFun _ = False
668 \end{code}
669
670 -----------------------------------------------------------------------------
671 SRT-related stuff
672
673 \begin{code}
674 staticClosureNeedsLink :: ClosureInfo -> Bool
675 -- A static closure needs a link field to aid the GC when traversing
676 -- the static closure graph.  But it only needs such a field if either
677 --      a) it has an SRT
678 --      b) it's a constructor with one or more pointer fields
679 -- In case (b), the constructor's fields themselves play the role
680 -- of the SRT.
681 staticClosureNeedsLink (ClosureInfo { closureSRT = srt })
682   = needsSRT srt
683 staticClosureNeedsLink (ConInfo { closureSMRep = sm_rep, closureCon = con })
684   = not (isNullaryRepDataCon con) && not_nocaf_constr
685   where
686     not_nocaf_constr = 
687         case sm_rep of 
688            GenericRep _ _ _ ConstrNoCaf -> False
689            _other                       -> True
690 \end{code}
691
692 Avoiding generating entries and info tables
693 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
694 At present, for every function we generate all of the following,
695 just in case.  But they aren't always all needed, as noted below:
696
697 [NB1: all of this applies only to *functions*.  Thunks always
698 have closure, info table, and entry code.]
699
700 [NB2: All are needed if the function is *exported*, just to play safe.]
701
702
703 * Fast-entry code  ALWAYS NEEDED
704
705 * Slow-entry code
706         Needed iff (a) we have any un-saturated calls to the function
707         OR         (b) the function is passed as an arg
708         OR         (c) we're in the parallel world and the function has free vars
709                         [Reason: in parallel world, we always enter functions
710                         with free vars via the closure.]
711
712 * The function closure
713         Needed iff (a) we have any un-saturated calls to the function
714         OR         (b) the function is passed as an arg
715         OR         (c) if the function has free vars (ie not top level)
716
717   Why case (a) here?  Because if the arg-satis check fails,
718   UpdatePAP stuffs a pointer to the function closure in the PAP.
719   [Could be changed; UpdatePAP could stuff in a code ptr instead,
720    but doesn't seem worth it.]
721
722   [NB: these conditions imply that we might need the closure
723   without the slow-entry code.  Here's how.
724
725         f x y = let g w = ...x..y..w...
726                 in
727                 ...(g t)...
728
729   Here we need a closure for g which contains x and y,
730   but since the calls are all saturated we just jump to the
731   fast entry point for g, with R1 pointing to the closure for g.]
732
733
734 * Standard info table
735         Needed iff (a) we have any un-saturated calls to the function
736         OR         (b) the function is passed as an arg
737         OR         (c) the function has free vars (ie not top level)
738
739         NB.  In the sequential world, (c) is only required so that the function closure has
740         an info table to point to, to keep the storage manager happy.
741         If (c) alone is true we could fake up an info table by choosing
742         one of a standard family of info tables, whose entry code just
743         bombs out.
744
745         [NB In the parallel world (c) is needed regardless because
746         we enter functions with free vars via the closure.]
747
748         If (c) is retained, then we'll sometimes generate an info table
749         (for storage mgr purposes) without slow-entry code.  Then we need
750         to use an error label in the info table to substitute for the absent
751         slow entry code.
752
753 \begin{code}
754 staticClosureRequired
755         :: Name
756         -> StgBinderInfo
757         -> LambdaFormInfo
758         -> Bool
759 staticClosureRequired binder bndr_info
760                       (LFReEntrant top_level _ _ _)     -- It's a function
761   = ASSERT( isTopLevel top_level )
762         -- Assumption: it's a top-level, no-free-var binding
763         not (satCallsOnly bndr_info)
764
765 staticClosureRequired binder other_binder_info other_lf_info = True
766 \end{code}
767
768 %************************************************************************
769 %*                                                                      *
770 \subsection[ClosureInfo-misc-funs]{Misc functions about @ClosureInfo@, etc.}
771 %*                                                                      *
772 %************************************************************************
773
774 \begin{code}
775
776 isStaticClosure :: ClosureInfo -> Bool
777 isStaticClosure cl_info = isStaticRep (closureSMRep cl_info)
778
779 closureUpdReqd :: ClosureInfo -> Bool
780 closureUpdReqd ClosureInfo{ closureLFInfo = lf_info } = lfUpdatable lf_info
781 closureUpdReqd ConInfo{} = False
782
783 lfUpdatable :: LambdaFormInfo -> Bool
784 lfUpdatable (LFThunk _ _ upd _ _)  = upd
785 lfUpdatable (LFBlackHole _)        = True
786         -- Black-hole closures are allocated to receive the results of an
787         -- alg case with a named default... so they need to be updated.
788 lfUpdatable _ = False
789
790 closureIsThunk :: ClosureInfo -> Bool
791 closureIsThunk ClosureInfo{ closureLFInfo = lf_info } = isLFThunk lf_info
792 closureIsThunk ConInfo{} = False
793
794 closureSingleEntry :: ClosureInfo -> Bool
795 closureSingleEntry (ClosureInfo { closureLFInfo = LFThunk _ _ upd _ _}) = not upd
796 closureSingleEntry other_closure = False
797
798 closureReEntrant :: ClosureInfo -> Bool
799 closureReEntrant (ClosureInfo { closureLFInfo = LFReEntrant _ _ _ _ }) = True
800 closureReEntrant other_closure = False
801
802 isConstrClosure_maybe :: ClosureInfo -> Maybe DataCon
803 isConstrClosure_maybe (ConInfo { closureCon = data_con }) = Just data_con
804 isConstrClosure_maybe _                                   = Nothing
805
806 closureFunInfo :: ClosureInfo -> Maybe (Int, ArgDescr)
807 closureFunInfo (ClosureInfo { closureLFInfo = LFReEntrant _ arity _ arg_desc})
808   = Just (arity, arg_desc)
809 closureFunInfo _
810   = Nothing
811 \end{code}
812
813 \begin{code}
814 isToplevClosure :: ClosureInfo -> Bool
815 isToplevClosure (ClosureInfo { closureLFInfo = lf_info })
816   = case lf_info of
817       LFReEntrant TopLevel _ _ _ -> True
818       LFThunk TopLevel _ _ _ _   -> True
819       other -> False
820 isToplevClosure _ = False
821 \end{code}
822
823 Label generation.
824
825 \begin{code}
826 infoTableLabelFromCI :: ClosureInfo -> CLabel
827 infoTableLabelFromCI (ClosureInfo { closureName = name,
828                                     closureLFInfo = lf_info, 
829                                     closureSMRep = rep })
830   = case lf_info of
831         LFBlackHole info -> info
832
833         LFThunk _ _ upd_flag (SelectorThunk offset) _ -> 
834                 mkSelectorInfoLabel upd_flag offset
835
836         LFThunk _ _ upd_flag (ApThunk arity) _ -> 
837                 mkApInfoTableLabel upd_flag arity
838
839         LFThunk{}      -> mkLocalInfoTableLabel name
840
841         LFReEntrant _ _ _ _ -> mkLocalInfoTableLabel name
842
843         other -> panic "infoTableLabelFromCI"
844
845 infoTableLabelFromCI (ConInfo { closureCon = con, 
846                                 closureSMRep = rep,
847                                 closureDllCon = dll })
848   | isStaticRep rep = mkStaticInfoTableLabel  name dll
849   | otherwise       = mkConInfoTableLabel     name dll
850   where
851     name = dataConName con
852
853 -- ClosureInfo for a closure (as opposed to a constructor) is always local
854 closureLabelFromCI (ClosureInfo { closureName = nm }) = mkLocalClosureLabel nm
855 closureLabelFromCI _ = panic "closureLabelFromCI"
856
857 -- thunkEntryLabel is a local help function, not exported.  It's used from both
858 -- entryLabelFromCI and getCallMethod.
859
860 thunkEntryLabel this_pkg thunk_id (ApThunk arity) is_updatable
861   = enterApLabel is_updatable arity
862 thunkEntryLabel this_pkg thunk_id (SelectorThunk offset) upd_flag
863   = enterSelectorLabel upd_flag offset
864 thunkEntryLabel this_pkg thunk_id _ is_updatable
865   = enterIdLabel this_pkg thunk_id
866
867 enterApLabel is_updatable arity
868   | tablesNextToCode = mkApInfoTableLabel is_updatable arity
869   | otherwise        = mkApEntryLabel is_updatable arity
870
871 enterSelectorLabel upd_flag offset
872   | tablesNextToCode = mkSelectorInfoLabel upd_flag offset
873   | otherwise        = mkSelectorEntryLabel upd_flag offset
874
875 enterIdLabel this_pkg id
876   | tablesNextToCode = mkInfoTableLabel this_pkg id
877   | otherwise        = mkEntryLabel this_pkg id
878
879 enterLocalIdLabel id
880   | tablesNextToCode = mkLocalInfoTableLabel id
881   | otherwise        = mkLocalEntryLabel id
882
883 enterReturnPtLabel name
884   | tablesNextToCode = mkReturnInfoLabel name
885   | otherwise        = mkReturnPtLabel name
886 \end{code}
887
888
889 We need a black-hole closure info to pass to @allocDynClosure@ when we
890 want to allocate the black hole on entry to a CAF.  These are the only
891 ways to build an LFBlackHole, maintaining the invariant that it really
892 is a black hole and not something else.
893
894 \begin{code}
895 cafBlackHoleClosureInfo (ClosureInfo { closureName = nm,
896                                        closureType = ty })
897   = ClosureInfo { closureName   = nm,
898                   closureLFInfo = LFBlackHole mkCAFBlackHoleInfoTableLabel,
899                   closureSMRep  = BlackHoleRep,
900                   closureSRT    = NoC_SRT,
901                   closureType   = ty,
902                   closureDescr  = "" }
903 cafBlackHoleClosureInfo _ = panic "cafBlackHoleClosureInfo"
904
905 seCafBlackHoleClosureInfo (ClosureInfo { closureName = nm,
906                                          closureType = ty })
907   = ClosureInfo { closureName   = nm,
908                   closureLFInfo = LFBlackHole mkSECAFBlackHoleInfoTableLabel,
909                   closureSMRep  = BlackHoleRep,
910                   closureSRT    = NoC_SRT,
911                   closureType   = ty,
912                   closureDescr  = ""  }
913 seCafBlackHoleClosureInfo _ = panic "seCafBlackHoleClosureInfo"
914 \end{code}
915
916 %************************************************************************
917 %*                                                                      *
918 \subsection[ClosureInfo-Profiling-funs]{Misc functions about for profiling info.}
919 %*                                                                      *
920 %************************************************************************
921
922 Profiling requires two pieces of information to be determined for
923 each closure's info table --- description and type.
924
925 The description is stored directly in the @CClosureInfoTable@ when the
926 info table is built.
927
928 The type is determined from the type information stored with the @Id@
929 in the closure info using @closureTypeDescr@.
930
931 \begin{code}
932 closureValDescr, closureTypeDescr :: ClosureInfo -> String
933 closureValDescr (ClosureInfo {closureDescr = descr}) 
934   = descr
935 closureValDescr (ConInfo {closureCon = con})
936   = occNameString (getOccName con)
937
938 closureTypeDescr (ClosureInfo { closureType = ty })
939   = getTyDescription ty
940 closureTypeDescr (ConInfo { closureCon = data_con })
941   = occNameString (getOccName (dataConTyCon data_con))
942
943 getTyDescription :: Type -> String
944 getTyDescription ty
945   = case (tcSplitSigmaTy ty) of { (_, _, tau_ty) ->
946     case tau_ty of
947       TyVarTy _              -> "*"
948       AppTy fun _            -> getTyDescription fun
949       FunTy _ res            -> '-' : '>' : fun_result res
950       TyConApp tycon _       -> getOccString tycon
951       NoteTy (FTVNote _) ty  -> getTyDescription ty
952       PredTy sty             -> getPredTyDescription sty
953       ForAllTy _ ty          -> getTyDescription ty
954     }
955   where
956     fun_result (FunTy _ res) = '>' : fun_result res
957     fun_result other         = getTyDescription other
958
959 getPredTyDescription (ClassP cl tys) = getOccString cl
960 getPredTyDescription (IParam ip ty)  = getOccString (ipNameName ip)
961 \end{code}