42bcabb9c28c6694c6146debf9c00e237c108cfd
[ghc-hetmet.git] / compiler / stgSyn / StgSyn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[StgSyn]{Shared term graph (STG) syntax for spineless-tagless code generation}
5
6 This data type represents programs just before code generation
7 (conversion to @AbstractC@): basically, what we have is a stylised
8 form of @CoreSyntax@, the style being one that happens to be ideally
9 suited to spineless tagless code generation.
10
11 \begin{code}
12 module StgSyn (
13         GenStgArg(..), 
14         GenStgLiveVars,
15
16         GenStgBinding(..), GenStgExpr(..), GenStgRhs(..),
17         GenStgAlt, AltType(..),
18
19         UpdateFlag(..), isUpdatable,
20
21         StgBinderInfo,
22         noBinderInfo, stgSatOcc, stgUnsatOcc, satCallsOnly,
23         combineStgBinderInfo,
24
25         -- a set of synonyms for the most common (only :-) parameterisation
26         StgArg, StgLiveVars,
27         StgBinding, StgExpr, StgRhs, StgAlt, 
28
29         -- StgOp
30         StgOp(..),
31
32         -- SRTs
33         SRT(..),
34
35         -- utils
36         stgBindHasCafRefs, stgArgHasCafRefs, stgRhsArity,
37         isDllConApp, isStgTypeArg,
38         stgArgType,
39
40         pprStgBinding, pprStgBindings, pprStgBindingsWithSRTs
41
42 #ifdef DEBUG
43         , pprStgLVs
44 #endif
45     ) where
46
47 #include "HsVersions.h"
48
49 import CostCentre       ( CostCentreStack, CostCentre )
50 import VarSet           ( IdSet, isEmptyVarSet )
51 import Var              ( isId )
52 import Id               ( Id, idName, idType, idCafInfo )
53 import IdInfo           ( mayHaveCafRefs )
54 import Packages         ( isDllName )
55 import Literal          ( Literal, literalType )
56 import ForeignCall      ( ForeignCall )
57 import DataCon          ( DataCon, dataConName )
58 import CoreSyn          ( AltCon )
59 import PprCore          ( {- instances -} )
60 import PrimOp           ( PrimOp )
61 import Outputable
62 import Util             ( count )
63 import Type             ( Type )
64 import TyCon            ( TyCon )
65 import UniqSet
66 import Unique           ( Unique )
67 import Bitmap
68 import StaticFlags      ( opt_SccProfilingOn )
69 import Module
70 import FastString
71 \end{code}
72
73 %************************************************************************
74 %*                                                                      *
75 \subsection{@GenStgBinding@}
76 %*                                                                      *
77 %************************************************************************
78
79 As usual, expressions are interesting; other things are boring.  Here
80 are the boring things [except note the @GenStgRhs@], parameterised
81 with respect to binder and occurrence information (just as in
82 @CoreSyn@):
83
84 There is one SRT for each group of bindings.
85
86 \begin{code}
87 data GenStgBinding bndr occ
88   = StgNonRec   bndr (GenStgRhs bndr occ)
89   | StgRec      [(bndr, GenStgRhs bndr occ)]
90 \end{code}
91
92 %************************************************************************
93 %*                                                                      *
94 \subsection{@GenStgArg@}
95 %*                                                                      *
96 %************************************************************************
97
98 \begin{code}
99 data GenStgArg occ
100   = StgVarArg   occ
101   | StgLitArg   Literal
102   | StgTypeArg  Type            -- For when we want to preserve all type info
103 \end{code}
104
105 \begin{code}
106 isStgTypeArg :: StgArg -> Bool
107 isStgTypeArg (StgTypeArg _) = True
108 isStgTypeArg _              = False
109
110 isDllArg :: PackageId -> StgArg -> Bool
111         -- Does this argument refer to something in a different DLL?
112 isDllArg this_pkg (StgVarArg v)  = isDllName this_pkg (idName v)
113 isDllArg _        _              = False
114
115 isDllConApp :: PackageId -> DataCon -> [StgArg] -> Bool
116         -- Does this constructor application refer to 
117         -- anything in a different DLL?
118         -- If so, we can't allocate it statically
119 isDllConApp this_pkg con args
120    = isDllName this_pkg (dataConName con) || any (isDllArg this_pkg) args
121
122 stgArgType :: StgArg -> Type
123         -- Very half baked becase we have lost the type arguments
124 stgArgType (StgVarArg v)   = idType v
125 stgArgType (StgLitArg lit) = literalType lit
126 stgArgType (StgTypeArg _)  = panic "stgArgType called on stgTypeArg"
127 \end{code}
128
129 %************************************************************************
130 %*                                                                      *
131 \subsection{STG expressions}
132 %*                                                                      *
133 %************************************************************************
134
135 The @GenStgExpr@ data type is parameterised on binder and occurrence
136 info, as before.
137
138 %************************************************************************
139 %*                                                                      *
140 \subsubsection{@GenStgExpr@ application}
141 %*                                                                      *
142 %************************************************************************
143
144 An application is of a function to a list of atoms [not expressions].
145 Operationally, we want to push the arguments on the stack and call the
146 function.  (If the arguments were expressions, we would have to build
147 their closures first.)
148
149 There is no constructor for a lone variable; it would appear as
150 @StgApp var [] _@.
151 \begin{code}
152 type GenStgLiveVars occ = UniqSet occ
153
154 data GenStgExpr bndr occ
155   = StgApp
156         occ             -- function
157         [GenStgArg occ] -- arguments; may be empty
158 \end{code}
159
160 %************************************************************************
161 %*                                                                      *
162 \subsubsection{@StgConApp@ and @StgPrimApp@---saturated applications}
163 %*                                                                      *
164 %************************************************************************
165
166 There are a specialised forms of application, for
167 constructors, primitives, and literals.
168 \begin{code}
169   | StgLit      Literal
170   
171         -- StgConApp is vital for returning unboxed tuples
172         -- which can't be let-bound first
173   | StgConApp   DataCon
174                 [GenStgArg occ] -- Saturated
175
176   | StgOpApp    StgOp           -- Primitive op or foreign call
177                 [GenStgArg occ] -- Saturated
178                 Type            -- Result type
179                                 -- We need to know this so that we can 
180                                 -- assign result registers
181 \end{code}
182
183 %************************************************************************
184 %*                                                                      *
185 \subsubsection{@StgLam@}
186 %*                                                                      *
187 %************************************************************************
188
189 StgLam is used *only* during CoreToStg's work.  Before CoreToStg has finished
190 it encodes (\x -> e) as (let f = \x -> e in f)
191
192 \begin{code}
193   | StgLam
194         Type            -- Type of whole lambda (useful when making a binder for it)
195         [bndr]
196         StgExpr         -- Body of lambda
197 \end{code}
198
199
200 %************************************************************************
201 %*                                                                      *
202 \subsubsection{@GenStgExpr@: case-expressions}
203 %*                                                                      *
204 %************************************************************************
205
206 This has the same boxed/unboxed business as Core case expressions.
207 \begin{code}
208   | StgCase
209         (GenStgExpr bndr occ)
210                         -- the thing to examine
211
212         (GenStgLiveVars occ) -- Live vars of whole case expression, 
213                         -- plus everything that happens after the case
214                         -- i.e., those which mustn't be overwritten
215
216         (GenStgLiveVars occ) -- Live vars of RHSs (plus what happens afterwards)
217                         -- i.e., those which must be saved before eval.
218                         --
219                         -- note that an alt's constructor's
220                         -- binder-variables are NOT counted in the
221                         -- free vars for the alt's RHS
222
223         bndr            -- binds the result of evaluating the scrutinee
224
225         SRT             -- The SRT for the continuation
226
227         AltType 
228
229         [GenStgAlt bndr occ]    -- The DEFAULT case is always *first* 
230                                 -- if it is there at all
231 \end{code}
232
233 %************************************************************************
234 %*                                                                      *
235 \subsubsection{@GenStgExpr@:  @let(rec)@-expressions}
236 %*                                                                      *
237 %************************************************************************
238
239 The various forms of let(rec)-expression encode most of the
240 interesting things we want to do.
241 \begin{enumerate}
242 \item
243 \begin{verbatim}
244 let-closure x = [free-vars] expr [args]
245 in e
246 \end{verbatim}
247 is equivalent to
248 \begin{verbatim}
249 let x = (\free-vars -> \args -> expr) free-vars
250 \end{verbatim}
251 \tr{args} may be empty (and is for most closures).  It isn't under
252 circumstances like this:
253 \begin{verbatim}
254 let x = (\y -> y+z)
255 \end{verbatim}
256 This gets mangled to
257 \begin{verbatim}
258 let-closure x = [z] [y] (y+z)
259 \end{verbatim}
260 The idea is that we compile code for @(y+z)@ in an environment in which
261 @z@ is bound to an offset from \tr{Node}, and @y@ is bound to an
262 offset from the stack pointer.
263
264 (A let-closure is an @StgLet@ with a @StgRhsClosure@ RHS.)
265
266 \item
267 \begin{verbatim}
268 let-constructor x = Constructor [args]
269 in e
270 \end{verbatim}
271
272 (A let-constructor is an @StgLet@ with a @StgRhsCon@ RHS.)
273
274 \item
275 Letrec-expressions are essentially the same deal as
276 let-closure/let-constructor, so we use a common structure and
277 distinguish between them with an @is_recursive@ boolean flag.
278
279 \item
280 \begin{verbatim}
281 let-unboxed u = an arbitrary arithmetic expression in unboxed values
282 in e
283 \end{verbatim}
284 All the stuff on the RHS must be fully evaluated.  No function calls either!
285
286 (We've backed away from this toward case-expressions with
287 suitably-magical alts ...)
288
289 \item
290 ~[Advanced stuff here!  Not to start with, but makes pattern matching
291 generate more efficient code.]
292
293 \begin{verbatim}
294 let-escapes-not fail = expr
295 in e'
296 \end{verbatim}
297 Here the idea is that @e'@ guarantees not to put @fail@ in a data structure,
298 or pass it to another function.  All @e'@ will ever do is tail-call @fail@.
299 Rather than build a closure for @fail@, all we need do is to record the stack
300 level at the moment of the @let-escapes-not@; then entering @fail@ is just
301 a matter of adjusting the stack pointer back down to that point and entering
302 the code for it.
303
304 Another example:
305 \begin{verbatim}
306 f x y = let z = huge-expression in
307         if y==1 then z else
308         if y==2 then z else
309         1
310 \end{verbatim}
311
312 (A let-escapes-not is an @StgLetNoEscape@.)
313
314 \item
315 We may eventually want:
316 \begin{verbatim}
317 let-literal x = Literal
318 in e
319 \end{verbatim}
320
321 (ToDo: is this obsolete?)
322 \end{enumerate}
323
324 And so the code for let(rec)-things:
325 \begin{code}
326   | StgLet
327         (GenStgBinding bndr occ)        -- right hand sides (see below)
328         (GenStgExpr bndr occ)           -- body
329
330   | StgLetNoEscape                      -- remember: ``advanced stuff''
331         (GenStgLiveVars occ)            -- Live in the whole let-expression
332                                         -- Mustn't overwrite these stack slots
333                                         --  *Doesn't* include binders of the let(rec).
334
335         (GenStgLiveVars occ)            -- Live in the right hand sides (only)
336                                         -- These are the ones which must be saved on
337                                         -- the stack if they aren't there already
338                                         --  *Does* include binders of the let(rec) if recursive.
339
340         (GenStgBinding bndr occ)        -- right hand sides (see below)
341         (GenStgExpr bndr occ)           -- body
342 \end{code}
343
344 %************************************************************************
345 %*                                                                      *
346 \subsubsection{@GenStgExpr@: @scc@ expressions}
347 %*                                                                      *
348 %************************************************************************
349
350 Finally for @scc@ expressions we introduce a new STG construct.
351
352 \begin{code}
353   | StgSCC
354         CostCentre              -- label of SCC expression
355         (GenStgExpr bndr occ)   -- scc expression
356 \end{code}
357
358 %************************************************************************
359 %*                                                                      *
360 \subsubsection{@GenStgExpr@: @hpc@ expressions}
361 %*                                                                      *
362 %************************************************************************
363
364 Finally for @scc@ expressions we introduce a new STG construct.
365
366 \begin{code}
367   | StgTick
368     Module                      -- the module of the source of this tick
369     Int                         -- tick number
370     (GenStgExpr bndr occ)       -- sub expression
371   -- end of GenStgExpr
372 \end{code}
373
374 %************************************************************************
375 %*                                                                      *
376 \subsection{STG right-hand sides}
377 %*                                                                      *
378 %************************************************************************
379
380 Here's the rest of the interesting stuff for @StgLet@s; the first
381 flavour is for closures:
382 \begin{code}
383 data GenStgRhs bndr occ
384   = StgRhsClosure
385         CostCentreStack         -- CCS to be attached (default is CurrentCCS)
386         StgBinderInfo           -- Info about how this binder is used (see below)
387         [occ]                   -- non-global free vars; a list, rather than
388                                 -- a set, because order is important
389         !UpdateFlag             -- ReEntrant | Updatable | SingleEntry
390         SRT                     -- The SRT reference
391         [bndr]                  -- arguments; if empty, then not a function;
392                                 -- as above, order is important.
393         (GenStgExpr bndr occ)   -- body
394 \end{code}
395 An example may be in order.  Consider:
396 \begin{verbatim}
397 let t = \x -> \y -> ... x ... y ... p ... q in e
398 \end{verbatim}
399 Pulling out the free vars and stylising somewhat, we get the equivalent:
400 \begin{verbatim}
401 let t = (\[p,q] -> \[x,y] -> ... x ... y ... p ...q) p q
402 \end{verbatim}
403 Stg-operationally, the @[x,y]@ are on the stack, the @[p,q]@ are
404 offsets from @Node@ into the closure, and the code ptr for the closure
405 will be exactly that in parentheses above.
406
407 The second flavour of right-hand-side is for constructors (simple but important):
408 \begin{code}
409   | StgRhsCon
410         CostCentreStack         -- CCS to be attached (default is CurrentCCS).
411                                 -- Top-level (static) ones will end up with
412                                 -- DontCareCCS, because we don't count static
413                                 -- data in heap profiles, and we don't set CCCS
414                                 -- from static closure.
415         DataCon                 -- constructor
416         [GenStgArg occ] -- args
417 \end{code}
418
419 \begin{code}
420 stgRhsArity :: StgRhs -> Int
421 stgRhsArity (StgRhsClosure _ _ _ _ _ bndrs _) = count isId bndrs
422   -- The arity never includes type parameters, so
423   -- when keeping type arguments and binders in the Stg syntax 
424   -- (opt_RuntimeTypes) we have to fliter out the type binders.
425 stgRhsArity (StgRhsCon _ _ _) = 0
426 \end{code}
427
428 \begin{code}
429 stgBindHasCafRefs :: GenStgBinding bndr Id -> Bool
430 stgBindHasCafRefs (StgNonRec _ rhs) = rhsHasCafRefs rhs
431 stgBindHasCafRefs (StgRec binds)    = any rhsHasCafRefs (map snd binds)
432
433 rhsHasCafRefs :: GenStgRhs bndr Id -> Bool
434 rhsHasCafRefs (StgRhsClosure _ _ _ upd srt _ _) 
435   = isUpdatable upd || nonEmptySRT srt
436 rhsHasCafRefs (StgRhsCon _ _ args)
437   = any stgArgHasCafRefs args
438
439 stgArgHasCafRefs :: GenStgArg Id -> Bool
440 stgArgHasCafRefs (StgVarArg id) = mayHaveCafRefs (idCafInfo id)
441 stgArgHasCafRefs _ = False
442 \end{code}
443
444 Here's the @StgBinderInfo@ type, and its combining op:
445 \begin{code}
446 data StgBinderInfo
447   = NoStgBinderInfo
448   | SatCallsOnly        -- All occurrences are *saturated* *function* calls
449                         -- This means we don't need to build an info table and 
450                         -- slow entry code for the thing
451                         -- Thunks never get this value
452
453 noBinderInfo, stgUnsatOcc, stgSatOcc :: StgBinderInfo
454 noBinderInfo = NoStgBinderInfo
455 stgUnsatOcc  = NoStgBinderInfo
456 stgSatOcc    = SatCallsOnly
457
458 satCallsOnly :: StgBinderInfo -> Bool
459 satCallsOnly SatCallsOnly    = True
460 satCallsOnly NoStgBinderInfo = False
461
462 combineStgBinderInfo :: StgBinderInfo -> StgBinderInfo -> StgBinderInfo
463 combineStgBinderInfo SatCallsOnly SatCallsOnly = SatCallsOnly
464 combineStgBinderInfo _            _            = NoStgBinderInfo
465
466 --------------
467 pp_binder_info :: StgBinderInfo -> SDoc
468 pp_binder_info NoStgBinderInfo = empty
469 pp_binder_info SatCallsOnly    = ptext SLIT("sat-only")
470 \end{code}
471
472 %************************************************************************
473 %*                                                                      *
474 \subsection[Stg-case-alternatives]{STG case alternatives}
475 %*                                                                      *
476 %************************************************************************
477
478 Very like in @CoreSyntax@ (except no type-world stuff).
479
480 The type constructor is guaranteed not to be abstract; that is, we can
481 see its representation.  This is important because the code generator
482 uses it to determine return conventions etc.  But it's not trivial
483 where there's a moduule loop involved, because some versions of a type
484 constructor might not have all the constructors visible.  So
485 mkStgAlgAlts (in CoreToStg) ensures that it gets the TyCon from the
486 constructors or literals (which are guaranteed to have the Real McCoy)
487 rather than from the scrutinee type.
488
489 \begin{code}
490 type GenStgAlt bndr occ
491   = (AltCon,            -- alts: data constructor,
492      [bndr],            -- constructor's parameters,
493      [Bool],            -- "use mask", same length as
494                         -- parameters; a True in a
495                         -- param's position if it is
496                         -- used in the ...
497      GenStgExpr bndr occ)       -- ...right-hand side.
498
499 data AltType
500   = PolyAlt             -- Polymorphic (a type variable)
501   | UbxTupAlt TyCon     -- Unboxed tuple
502   | AlgAlt    TyCon     -- Algebraic data type; the AltCons will be DataAlts
503   | PrimAlt   TyCon     -- Primitive data type; the AltCons will be LitAlts
504 \end{code}
505
506 %************************************************************************
507 %*                                                                      *
508 \subsection[Stg]{The Plain STG parameterisation}
509 %*                                                                      *
510 %************************************************************************
511
512 This happens to be the only one we use at the moment.
513
514 \begin{code}
515 type StgBinding     = GenStgBinding     Id Id
516 type StgArg         = GenStgArg         Id
517 type StgLiveVars    = GenStgLiveVars    Id
518 type StgExpr        = GenStgExpr        Id Id
519 type StgRhs         = GenStgRhs         Id Id
520 type StgAlt         = GenStgAlt         Id Id
521 \end{code}
522
523 %************************************************************************
524 %*                                                                      *
525 \subsubsection[UpdateFlag-datatype]{@UpdateFlag@}
526 %*                                                                      *
527 %************************************************************************
528
529 This is also used in @LambdaFormInfo@ in the @ClosureInfo@ module.
530
531 A @ReEntrant@ closure may be entered multiple times, but should not be
532 updated or blackholed.  An @Updatable@ closure should be updated after
533 evaluation (and may be blackholed during evaluation).  A @SingleEntry@
534 closure will only be entered once, and so need not be updated but may
535 safely be blackholed.
536
537 \begin{code}
538 data UpdateFlag = ReEntrant | Updatable | SingleEntry
539
540 instance Outputable UpdateFlag where
541     ppr u
542       = char (case u of { ReEntrant -> 'r';  Updatable -> 'u';  SingleEntry -> 's' })
543
544 isUpdatable :: UpdateFlag -> Bool
545 isUpdatable ReEntrant   = False
546 isUpdatable SingleEntry = False
547 isUpdatable Updatable   = True
548 \end{code}
549
550 %************************************************************************
551 %*                                                                      *
552 \subsubsection{StgOp}
553 %*                                                                      *
554 %************************************************************************
555
556 An StgOp allows us to group together PrimOps and ForeignCalls.
557 It's quite useful to move these around together, notably
558 in StgOpApp and COpStmt.
559
560 \begin{code}
561 data StgOp = StgPrimOp  PrimOp
562
563            | StgFCallOp ForeignCall Unique
564                 -- The Unique is occasionally needed by the C pretty-printer
565                 -- (which lacks a unique supply), notably when generating a
566                 -- typedef for foreign-export-dynamic
567 \end{code}
568
569
570 %************************************************************************
571 %*                                                                      *
572 \subsubsection[Static Reference Tables]{@SRT@}
573 %*                                                                      *
574 %************************************************************************
575
576 There is one SRT per top-level function group.  Each local binding and
577 case expression within this binding group has a subrange of the whole
578 SRT, expressed as an offset and length.
579
580 In CoreToStg we collect the list of CafRefs at each SRT site, which is later 
581 converted into the length and offset form by the SRT pass.
582
583 \begin{code}
584 data SRT = NoSRT
585          | SRTEntries IdSet
586                 -- generated by CoreToStg
587          | SRT !Int{-offset-} !Int{-length-} !Bitmap{-bitmap-}
588                 -- generated by computeSRTs
589
590 nonEmptySRT :: SRT -> Bool
591 nonEmptySRT NoSRT           = False
592 nonEmptySRT (SRTEntries vs) = not (isEmptyVarSet vs)
593 nonEmptySRT _               = True
594
595 pprSRT :: SRT -> SDoc
596 pprSRT (NoSRT)          = ptext SLIT("_no_srt_")
597 pprSRT (SRTEntries ids) = text "SRT:" <> ppr ids
598 pprSRT (SRT off _ _)    = parens (ppr off <> comma <> text "*bitmap*")
599 \end{code}
600
601 %************************************************************************
602 %*                                                                      *
603 \subsection[Stg-pretty-printing]{Pretty-printing}
604 %*                                                                      *
605 %************************************************************************
606
607 Robin Popplestone asked for semi-colon separators on STG binds; here's
608 hoping he likes terminators instead...  Ditto for case alternatives.
609
610 \begin{code}
611 pprGenStgBinding :: (Outputable bndr, Outputable bdee, Ord bdee)
612                  => GenStgBinding bndr bdee -> SDoc
613
614 pprGenStgBinding (StgNonRec bndr rhs)
615   = hang (hsep [ppr bndr, equals])
616         4 ((<>) (ppr rhs) semi)
617
618 pprGenStgBinding (StgRec pairs)
619   = vcat ((ifPprDebug (ptext SLIT("{- StgRec (begin) -}"))) :
620            (map (ppr_bind) pairs) ++ [(ifPprDebug (ptext SLIT("{- StgRec (end) -}")))])
621   where
622     ppr_bind (bndr, expr)
623       = hang (hsep [ppr bndr, equals])
624              4 ((<>) (ppr expr) semi)
625
626 pprStgBinding  :: StgBinding -> SDoc
627 pprStgBinding  bind  = pprGenStgBinding bind
628
629 pprStgBindings :: [StgBinding] -> SDoc
630 pprStgBindings binds = vcat (map pprGenStgBinding binds)
631
632 pprGenStgBindingWithSRT  
633         :: (Outputable bndr, Outputable bdee, Ord bdee) 
634         => (GenStgBinding bndr bdee,[(Id,[Id])]) -> SDoc
635
636 pprGenStgBindingWithSRT (bind,srts)
637   = vcat (pprGenStgBinding bind : map pprSRT srts)
638   where pprSRT (id,srt) = 
639            ptext SLIT("SRT") <> parens (ppr id) <> ptext SLIT(": ") <> ppr srt
640
641 pprStgBindingsWithSRTs :: [(StgBinding,[(Id,[Id])])] -> SDoc
642 pprStgBindingsWithSRTs binds = vcat (map pprGenStgBindingWithSRT binds)
643 \end{code}
644
645 \begin{code}
646 instance (Outputable bdee) => Outputable (GenStgArg bdee) where
647     ppr = pprStgArg
648
649 instance (Outputable bndr, Outputable bdee, Ord bdee)
650                 => Outputable (GenStgBinding bndr bdee) where
651     ppr = pprGenStgBinding
652
653 instance (Outputable bndr, Outputable bdee, Ord bdee)
654                 => Outputable (GenStgExpr bndr bdee) where
655     ppr = pprStgExpr
656
657 instance (Outputable bndr, Outputable bdee, Ord bdee)
658                 => Outputable (GenStgRhs bndr bdee) where
659     ppr rhs = pprStgRhs rhs
660 \end{code}
661
662 \begin{code}
663 pprStgArg :: (Outputable bdee) => GenStgArg bdee -> SDoc
664
665 pprStgArg (StgVarArg var) = ppr var
666 pprStgArg (StgLitArg con) = ppr con
667 pprStgArg (StgTypeArg ty) = char '@' <+> ppr ty
668 \end{code}
669
670 \begin{code}
671 pprStgExpr :: (Outputable bndr, Outputable bdee, Ord bdee)
672            => GenStgExpr bndr bdee -> SDoc
673 -- special case
674 pprStgExpr (StgLit lit)     = ppr lit
675
676 -- general case
677 pprStgExpr (StgApp func args)
678   = hang (ppr func)
679          4 (sep (map (ppr) args))
680 \end{code}
681
682 \begin{code}
683 pprStgExpr (StgConApp con args)
684   = hsep [ ppr con, brackets (interppSP args)]
685
686 pprStgExpr (StgOpApp op args _)
687   = hsep [ pprStgOp op, brackets (interppSP args)]
688
689 pprStgExpr (StgLam _ bndrs body)
690   =sep [ char '\\' <+> ppr bndrs <+> ptext SLIT("->"),
691          pprStgExpr body ]
692 \end{code}
693
694 \begin{code}
695 -- special case: let v = <very specific thing>
696 --               in
697 --               let ...
698 --               in
699 --               ...
700 --
701 -- Very special!  Suspicious! (SLPJ)
702
703 {-
704 pprStgExpr (StgLet srt (StgNonRec bndr (StgRhsClosure cc bi free_vars upd_flag args rhs))
705                         expr@(StgLet _ _))
706   = ($$)
707       (hang (hcat [ptext SLIT("let { "), ppr bndr, ptext SLIT(" = "),
708                           ppr cc,
709                           pp_binder_info bi,
710                           ptext SLIT(" ["), ifPprDebug (interppSP free_vars), ptext SLIT("] \\"),
711                           ppr upd_flag, ptext SLIT(" ["),
712                           interppSP args, char ']'])
713             8 (sep [hsep [ppr rhs, ptext SLIT("} in")]]))
714       (ppr expr)
715 -}
716
717 -- special case: let ... in let ...
718
719 pprStgExpr (StgLet bind expr@(StgLet _ _))
720   = ($$)
721       (sep [hang (ptext SLIT("let {"))
722                 2 (hsep [pprGenStgBinding bind, ptext SLIT("} in")])])
723       (ppr expr)
724
725 -- general case
726 pprStgExpr (StgLet bind expr)
727   = sep [hang (ptext SLIT("let {")) 2 (pprGenStgBinding bind),
728            hang (ptext SLIT("} in ")) 2 (ppr expr)]
729
730 pprStgExpr (StgLetNoEscape lvs_whole lvs_rhss bind expr)
731   = sep [hang (ptext SLIT("let-no-escape {"))
732                 2 (pprGenStgBinding bind),
733            hang ((<>) (ptext SLIT("} in "))
734                    (ifPprDebug (
735                     nest 4 (
736                       hcat [ptext  SLIT("-- lvs: ["), interppSP (uniqSetToList lvs_whole),
737                              ptext SLIT("]; rhs lvs: ["), interppSP (uniqSetToList lvs_rhss),
738                              char ']']))))
739                 2 (ppr expr)]
740
741 pprStgExpr (StgSCC cc expr)
742   = sep [ hsep [ptext SLIT("_scc_"), ppr cc],
743           pprStgExpr expr ]
744
745 pprStgExpr (StgTick m n expr)
746   = sep [ hsep [ptext SLIT("_tick_"),  pprModule m,text (show n)],
747           pprStgExpr expr ]
748
749 pprStgExpr (StgCase expr lvs_whole lvs_rhss bndr srt alt_type alts)
750   = sep [sep [ptext SLIT("case"),
751            nest 4 (hsep [pprStgExpr expr,
752              ifPprDebug (dcolon <+> ppr alt_type)]),
753            ptext SLIT("of"), ppr bndr, char '{'],
754            ifPprDebug (
755            nest 4 (
756              hcat [ptext  SLIT("-- lvs: ["), interppSP (uniqSetToList lvs_whole),
757                     ptext SLIT("]; rhs lvs: ["), interppSP (uniqSetToList lvs_rhss),
758                     ptext SLIT("]; "),
759                     pprMaybeSRT srt])),
760            nest 2 (vcat (map pprStgAlt alts)),
761            char '}']
762
763 pprStgAlt :: (Outputable bndr, Outputable occ, Ord occ)
764           => GenStgAlt bndr occ -> SDoc
765 pprStgAlt (con, params, _use_mask, expr)
766   = hang (hsep [ppr con, interppSP params, ptext SLIT("->")])
767          4 (ppr expr <> semi)
768
769 pprStgOp :: StgOp -> SDoc
770 pprStgOp (StgPrimOp  op)   = ppr op
771 pprStgOp (StgFCallOp op _) = ppr op
772
773 instance Outputable AltType where
774   ppr PolyAlt        = ptext SLIT("Polymorphic")
775   ppr (UbxTupAlt tc) = ptext SLIT("UbxTup") <+> ppr tc
776   ppr (AlgAlt tc)    = ptext SLIT("Alg")    <+> ppr tc
777   ppr (PrimAlt tc)   = ptext SLIT("Prim")   <+> ppr tc
778 \end{code}
779
780 \begin{code}
781 #ifdef DEBUG
782 pprStgLVs :: Outputable occ => GenStgLiveVars occ -> SDoc
783 pprStgLVs lvs
784   = getPprStyle $ \ sty ->
785     if userStyle sty || isEmptyUniqSet lvs then
786         empty
787     else
788         hcat [text "{-lvs:", interpp'SP (uniqSetToList lvs), text "-}"]
789 #endif
790 \end{code}
791
792 \begin{code}
793 pprStgRhs :: (Outputable bndr, Outputable bdee, Ord bdee)
794           => GenStgRhs bndr bdee -> SDoc
795
796 -- special case
797 pprStgRhs (StgRhsClosure cc bi [free_var] upd_flag srt [{-no args-}] (StgApp func []))
798   = hcat [ ppr cc,
799            pp_binder_info bi,
800            brackets (ifPprDebug (ppr free_var)),
801            ptext SLIT(" \\"), ppr upd_flag, pprMaybeSRT srt, ptext SLIT(" [] "), ppr func ]
802
803 -- general case
804 pprStgRhs (StgRhsClosure cc bi free_vars upd_flag srt args body)
805   = hang (hsep [if opt_SccProfilingOn then ppr cc else empty,
806                 pp_binder_info bi,
807                 ifPprDebug (brackets (interppSP free_vars)),
808                 char '\\' <> ppr upd_flag, pprMaybeSRT srt, brackets (interppSP args)])
809          4 (ppr body)
810
811 pprStgRhs (StgRhsCon cc con args)
812   = hcat [ ppr cc,
813            space, ppr con, ptext SLIT("! "), brackets (interppSP args)]
814
815 pprMaybeSRT :: SRT -> SDoc
816 pprMaybeSRT (NoSRT) = empty
817 pprMaybeSRT srt     = ptext SLIT("srt:") <> pprSRT srt
818 \end{code}