[project @ 1997-07-25 23:24:17 by sof]
[ghc-hetmet.git] / ghc / compiler / main / CmdLineOpts.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1996
3 %
4 \section[CmdLineOpts]{Things to do with command-line options}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module CmdLineOpts (
10         CoreToDo(..),
11         SimplifierSwitch(..),
12         StgToDo(..),
13         SwitchResult(..),
14         classifyOpts,
15
16         intSwitchSet,
17         switchIsOn,
18
19         maybe_CompilingGhcInternals,
20         opt_AllDemanded,
21         opt_AllStrict,
22         opt_AutoSccsOnAllToplevs,
23         opt_AutoSccsOnExportedToplevs,
24         opt_AutoSccsOnIndividualCafs,
25         opt_CompilingGhcInternals,
26         opt_D_dump_absC,
27         opt_D_dump_asm,
28         opt_D_dump_deforest,
29         opt_D_dump_deriv,
30         opt_D_dump_ds,
31         opt_D_dump_flatC,
32         opt_D_dump_occur_anal,
33         opt_D_dump_rdr,
34         opt_D_dump_realC,
35         opt_D_dump_rn,
36         opt_D_dump_simpl,
37         opt_D_dump_simpl_iterations,
38         opt_D_dump_spec,
39         opt_D_dump_stg,
40         opt_D_dump_stranal,
41         opt_D_dump_tc,
42         opt_D_show_passes,
43         opt_D_show_rn_trace,
44         opt_D_simplifier_stats,
45         opt_D_source_stats,
46         opt_D_verbose_core2core,
47         opt_D_verbose_stg2stg,
48         opt_DoCoreLinting,
49         opt_DoStgLinting,
50         opt_DoSemiTagging,
51         opt_DoEtaReduction,
52         opt_DoTickyProfiling,
53         opt_EnsureSplittableC,
54         opt_FoldrBuildOn,
55         opt_FoldrBuildTrace,
56         opt_ForConcurrent,
57         opt_GlasgowExts,
58         opt_GranMacros,
59         opt_Haskell_1_3,
60         opt_HiMap,
61         opt_IgnoreIfacePragmas,
62         opt_IgnoreStrictnessPragmas,
63         opt_IrrefutableEverything,
64         opt_IrrefutableTuples,
65         opt_LiberateCaseThreshold,
66         opt_NoImplicitPrelude,
67         opt_NumbersStrict,
68         opt_OmitBlackHoling,
69         opt_OmitDefaultInstanceMethods,
70         opt_OmitInterfacePragmas,
71         opt_PprStyle_All,
72         opt_PprStyle_Debug,
73         opt_PprStyle_User,
74         opt_PprUserLength,
75         opt_ProduceC,
76         opt_ProduceHi,
77         opt_ProduceS,
78         opt_ReportWhyUnfoldingsDisallowed,
79         opt_ReturnInRegsThreshold,
80         opt_SccGroup,
81         opt_SccProfilingOn,
82         opt_ShowImportSpecs,
83         opt_ShowPragmaNameErrs,
84         opt_SigsRequired,
85         opt_SourceUnchanged,
86         opt_SpecialiseAll,
87         opt_SpecialiseImports,
88         opt_SpecialiseOverloaded,
89         opt_SpecialiseTrace,
90         opt_SpecialiseUnboxed,
91         opt_StgDoLetNoEscapes,
92
93         opt_InterfaceUnfoldThreshold,
94         opt_UnfoldingCreationThreshold,
95         opt_UnfoldingConDiscount,
96         opt_UnfoldingUseThreshold,
97
98         opt_Verbose,
99         opt_WarnNameShadowing,
100         opt_WarnUnusedNames,
101         opt_WarnIncompletePatterns, opt_WarnOverlappedPatterns,
102         opt_PruneTyDecls, opt_PruneInstDecls,
103         opt_D_show_unused_imports,
104         opt_D_show_rn_stats,
105         
106         all_toplev_ids_visible
107     ) where
108
109 IMPORT_1_3(Array(array, (//)))
110 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
111 import PreludeGlaST     -- bad bad bad boy, Will (_Array internals)
112 #else
113 import GlaExts
114 import ArrBase
115 -- 2.04 and later exports Lift from GlaExts
116 #if __GLASGOW_HASKELL__ < 204
117 import PrelBase (Lift(..))
118 #endif
119 #endif
120 import Argv
121
122 CHK_Ubiq() -- debugging consistency check
123
124 import Constants        -- Default values for some flags
125
126 import Maybes           ( assocMaybe, firstJust, maybeToBool )
127 import Util             ( startsWith, panic, panic#, assertPanic )
128 \end{code}
129
130 A command-line {\em switch} is (generally) either on or off; e.g., the
131 ``verbose'' (-v) switch is either on or off.  (The \tr{-G<group>}
132 switch is an exception; it's set to a string, or nothing.)
133
134 A list of {\em ToDo}s is things to be done in a particular part of
135 processing.  A (fictitious) example for the Core-to-Core simplifier
136 might be: run the simplifier, then run the strictness analyser, then
137 run the simplifier again (three ``todos'').
138
139 There are three ``to-do processing centers'' at the moment.  In the
140 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
141 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
142 (\tr{simplStg/SimplStg.lhs}).
143
144 %************************************************************************
145 %*                                                                      *
146 \subsection{Datatypes associated with command-line options}
147 %*                                                                      *
148 %************************************************************************
149
150 \begin{code}
151 data SwitchResult
152   = SwBool      Bool            -- on/off
153   | SwString    FAST_STRING     -- nothing or a String
154   | SwInt       Int             -- nothing or an Int
155 \end{code}
156
157 \begin{code}
158 data CoreToDo           -- These are diff core-to-core passes,
159                         -- which may be invoked in any order,
160                         -- as many times as you like.
161
162   = CoreDoSimplify      -- The core-to-core simplifier.
163         (SimplifierSwitch -> SwitchResult)
164                         -- Each run of the simplifier can take a different
165                         -- set of simplifier-specific flags.
166   | CoreDoCalcInlinings1
167   | CoreDoCalcInlinings2
168   | CoreDoFloatInwards
169   | CoreDoFullLaziness
170   | CoreLiberateCase
171   | CoreDoPrintCore
172   | CoreDoStaticArgs
173   | CoreDoStrictness
174   | CoreDoSpecialising
175   | CoreDoDeforest
176   | CoreDoFoldrBuildWorkerWrapper
177   | CoreDoFoldrBuildWWAnal
178 \end{code}
179
180 \begin{code}
181 data StgToDo
182   = StgDoStaticArgs
183   | StgDoUpdateAnalysis
184   | StgDoLambdaLift
185   | StgDoMassageForProfiling  -- should be (next to) last
186   -- There's also setStgVarInfo, but its absolute "lastness"
187   -- is so critical that it is hardwired in (no flag).
188   | D_stg_stats
189 \end{code}
190
191 \begin{code}
192 data SimplifierSwitch
193   = SimplOkToDupCode
194   | SimplFloatLetsExposingWHNF
195   | SimplOkToFloatPrimOps
196   | SimplAlwaysFloatLetsFromLets
197   | SimplDoCaseElim
198   | SimplReuseCon
199   | SimplCaseOfCase
200   | SimplLetToCase
201   | SimplMayDeleteConjurableIds
202   | SimplPedanticBottoms -- see Simplifier for an explanation
203   | SimplDoArityExpand   -- expand arity of bindings
204   | SimplDoFoldrBuild    -- This is the per-simplification flag;
205                          -- see also FoldrBuildOn, used elsewhere
206                          -- in the compiler.
207   | SimplDoInlineFoldrBuild
208                          -- inline foldr/build (*after* f/b rule is used)
209
210   | IgnoreINLINEPragma
211   | SimplDoLambdaEtaExpansion
212
213   | EssentialUnfoldingsOnly -- never mind the thresholds, only
214                             -- do unfoldings that *must* be done
215                             -- (to saturate constructors and primitives)
216
217   | ShowSimplifierProgress  -- report counts on every interation
218
219   | MaxSimplifierIterations Int
220
221   | KeepSpecPragmaIds       -- We normally *toss* Ids we can do without
222   | KeepUnusedBindings
223
224   | SimplNoLetFromCase      -- used when turning off floating entirely
225   | SimplNoLetFromApp       -- (for experimentation only) WDP 95/10
226   | SimplNoLetFromStrictLet
227
228   | SimplDontFoldBackAppend
229                         -- we fold `foldr (:)' back into flip (++),
230                         -- but we *don't* want to do it when compiling
231                         -- List.hs, otherwise
232                         -- xs ++ ys = foldr (:) ys xs
233                         -- {- via our loopback -}
234                         -- xs ++ ys = xs ++ ys
235                         -- Oops!
236                         -- So only use this flag inside List.hs
237                         -- (Sigh, what a HACK, Andy.  WDP 96/01)
238
239   | SimplCaseMerge
240   | SimplCaseScrutinee  -- This flag tells that the expression being simplified is
241                         -- the scrutinee of a case expression, so we should
242                         -- apply the scrutinee discount when considering inlinings.
243                         -- See SimplVar.lhs
244 \end{code}
245
246 %************************************************************************
247 %*                                                                      *
248 \subsection{Classifying command-line options}
249 %*                                                                      *
250 %************************************************************************
251
252 \begin{code}
253 lookUp         :: FAST_STRING -> Bool
254 lookup_int     :: String -> Maybe Int
255 lookup_def_int :: String -> Int -> Int
256 lookup_str     :: String -> Maybe String
257
258 lookUp     sw = maybeToBool (assoc_opts sw)
259         
260 lookup_str sw = firstJust (map (startsWith sw) unpacked_opts)
261
262 lookup_int sw = case (lookup_str sw) of
263                   Nothing -> Nothing
264                   Just xx -> Just (read xx)
265
266 lookup_def_int sw def = case (lookup_str sw) of
267                             Nothing -> def              -- Use default
268                             Just xx -> read xx
269
270 assoc_opts    = assocMaybe [ (a, True) | a <- argv ]
271 unpacked_opts = map _UNPK_ argv
272 \end{code}
273
274 \begin{code}
275 opt_AllDemanded                 = lookUp  SLIT("-fall-demanded")
276 opt_AllStrict                   = lookUp  SLIT("-fall-strict")
277 opt_AutoSccsOnAllToplevs        = lookUp  SLIT("-fauto-sccs-on-all-toplevs")
278 opt_AutoSccsOnExportedToplevs   = lookUp  SLIT("-fauto-sccs-on-exported-toplevs")
279 opt_AutoSccsOnIndividualCafs    = lookUp  SLIT("-fauto-sccs-on-individual-cafs")
280 opt_CompilingGhcInternals       = maybeToBool maybe_CompilingGhcInternals
281 maybe_CompilingGhcInternals     = lookup_str "-fcompiling-ghc-internals="
282 opt_D_dump_absC                 = lookUp  SLIT("-ddump-absC")
283 opt_D_dump_asm                  = lookUp  SLIT("-ddump-asm")
284 opt_D_dump_deforest             = lookUp  SLIT("-ddump-deforest")
285 opt_D_dump_deriv                = lookUp  SLIT("-ddump-deriv")
286 opt_D_dump_ds                   = lookUp  SLIT("-ddump-ds")
287 opt_D_dump_flatC                = lookUp  SLIT("-ddump-flatC")
288 opt_D_dump_occur_anal           = lookUp  SLIT("-ddump-occur-anal")
289 opt_D_dump_rdr                  = lookUp  SLIT("-ddump-rdr")
290 opt_D_dump_realC                = lookUp  SLIT("-ddump-realC")
291 opt_D_dump_rn                   = lookUp  SLIT("-ddump-rn")
292 opt_D_dump_simpl                = lookUp  SLIT("-ddump-simpl")
293 opt_D_dump_simpl_iterations     = lookUp  SLIT("-ddump-simpl-iterations")
294 opt_D_dump_spec                 = lookUp  SLIT("-ddump-spec")
295 opt_D_dump_stg                  = lookUp  SLIT("-ddump-stg")
296 opt_D_dump_stranal              = lookUp  SLIT("-ddump-stranal")
297 opt_D_dump_tc                   = lookUp  SLIT("-ddump-tc")
298 opt_D_show_passes               = lookUp  SLIT("-dshow-passes")
299 opt_D_show_rn_trace             = lookUp  SLIT("-dshow-rn-trace")
300 opt_D_simplifier_stats          = lookUp  SLIT("-dsimplifier-stats")
301 opt_D_source_stats              = lookUp  SLIT("-dsource-stats")
302 opt_D_verbose_core2core         = lookUp  SLIT("-dverbose-simpl")
303 opt_D_verbose_stg2stg           = lookUp  SLIT("-dverbose-stg")
304 opt_DoCoreLinting               = lookUp  SLIT("-dcore-lint")
305 opt_DoStgLinting                = lookUp  SLIT("-dstg-lint")
306 opt_DoSemiTagging               = lookUp  SLIT("-fsemi-tagging")
307 opt_DoTickyProfiling            = lookUp  SLIT("-fticky-ticky")
308 opt_DoEtaReduction              = lookUp  SLIT("-fdo-eta-reduction")
309 opt_EnsureSplittableC           = lookUp  SLIT("-fglobalise-toplev-names")
310 opt_FoldrBuildOn                = lookUp  SLIT("-ffoldr-build-on")
311 opt_FoldrBuildTrace             = lookUp  SLIT("-ffoldr-build-trace")
312 opt_ForConcurrent               = lookUp  SLIT("-fconcurrent")
313 opt_GranMacros                  = lookUp  SLIT("-fgransim")
314 opt_GlasgowExts                 = lookUp  SLIT("-fglasgow-exts")
315 opt_Haskell_1_3                 = lookUp  SLIT("-fhaskell-1.3")
316 opt_HiMap                       = lookup_str "-himap="  -- file saying where to look for .hi files
317 opt_IgnoreIfacePragmas          = lookUp  SLIT("-fignore-interface-pragmas")
318 opt_IgnoreStrictnessPragmas     = lookUp  SLIT("-fignore-strictness-pragmas")
319 opt_IrrefutableEverything       = lookUp  SLIT("-firrefutable-everything")
320 opt_IrrefutableTuples           = lookUp  SLIT("-firrefutable-tuples")
321 opt_NoImplicitPrelude           = lookUp  SLIT("-fno-implicit-prelude")
322 opt_NumbersStrict               = lookUp  SLIT("-fnumbers-strict")
323 opt_OmitBlackHoling             = lookUp  SLIT("-dno-black-holing")
324 opt_OmitDefaultInstanceMethods  = lookUp  SLIT("-fomit-default-instance-methods")
325 opt_OmitInterfacePragmas        = lookUp  SLIT("-fomit-interface-pragmas")
326 opt_PprStyle_All                = lookUp  SLIT("-dppr-all")
327 opt_PprStyle_Debug              = lookUp  SLIT("-dppr-debug")
328 opt_PprStyle_User               = lookUp  SLIT("-dppr-user")
329 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
330 opt_ProduceC                    = lookup_str "-C="
331 opt_ProduceS                    = lookup_str "-S="
332 opt_ProduceHi                   = lookup_str "-hifile=" -- the one to produce this time 
333 opt_ReportWhyUnfoldingsDisallowed= lookUp SLIT("-freport-disallowed-unfoldings")
334 opt_SccProfilingOn              = lookUp  SLIT("-fscc-profiling")
335 opt_ShowImportSpecs             = lookUp  SLIT("-fshow-import-specs")
336 opt_ShowPragmaNameErrs          = lookUp  SLIT("-fshow-pragma-name-errs")
337 opt_SigsRequired                = lookUp  SLIT("-fsignatures-required")
338 opt_SourceUnchanged             = lookUp  SLIT("-fsource-unchanged")
339 opt_SpecialiseAll               = lookUp  SLIT("-fspecialise-all")
340 opt_SpecialiseImports           = lookUp  SLIT("-fspecialise-imports")
341 opt_SpecialiseOverloaded        = lookUp  SLIT("-fspecialise-overloaded")
342 opt_SpecialiseTrace             = lookUp  SLIT("-ftrace-specialisation")
343 opt_SpecialiseUnboxed           = lookUp  SLIT("-fspecialise-unboxed")
344 opt_StgDoLetNoEscapes           = lookUp  SLIT("-flet-no-escape")
345 opt_ReturnInRegsThreshold       = lookup_int "-freturn-in-regs-threshold"
346 opt_SccGroup                    = lookup_str "-G="
347 opt_Verbose                     = lookUp  SLIT("-v")
348
349 opt_InterfaceUnfoldThreshold    = lookup_def_int "-funfolding-interface-threshold" iNTERFACE_UNFOLD_THRESHOLD
350 opt_UnfoldingCreationThreshold  = lookup_def_int "-funfolding-creation-threshold"  uNFOLDING_CREATION_THRESHOLD
351 opt_UnfoldingUseThreshold       = lookup_def_int "-funfolding-use-threshold"       uNFOLDING_USE_THRESHOLD
352 opt_UnfoldingConDiscount        = lookup_def_int "-funfolding-con-discount"        uNFOLDING_CON_DISCOUNT_WEIGHT
353                         
354 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold"       lIBERATE_CASE_THRESHOLD
355 opt_WarnNameShadowing           = lookUp  SLIT("-fwarn-name-shadowing")
356 opt_WarnIncompletePatterns      = not (lookUp  SLIT("-fno-warn-incomplete-patterns"))
357 opt_WarnOverlappedPatterns      = not (lookUp  SLIT("-fno-warn-overlapped-patterns"))
358 opt_WarnUnusedNames             = lookUp  SLIT("-fwarn-unused-names")
359 opt_PruneTyDecls                = not (lookUp SLIT("-fno-prune-tydecls"))
360 opt_PruneInstDecls              = not (lookUp SLIT("-fno-prune-instdecls"))
361 opt_D_show_unused_imports       = lookUp SLIT("-dshow-unused-imports")
362 opt_D_show_rn_stats             = lookUp SLIT("-dshow-rn-stats")
363
364 -- opt_UnfoldingOverrideThreshold       = lookup_int "-funfolding-override-threshold"
365 \end{code}
366
367
368 \begin{code}
369 all_toplev_ids_visible :: Bool
370 all_toplev_ids_visible = 
371   not opt_OmitInterfacePragmas ||  -- Pragmas can make them visible
372   opt_EnsureSplittableC        ||  -- Splitting requires visiblilty
373   opt_AutoSccsOnAllToplevs         -- ditto for profiling 
374                                    -- (ToDo: fix up the auto-annotation
375                                    -- pass in the desugarer to avoid having
376                                    -- to do this)
377
378 \end{code}
379
380
381
382 \begin{code}
383 classifyOpts :: ([CoreToDo],    -- Core-to-Core processing spec
384                  [StgToDo])     -- STG-to-STG   processing spec
385
386 classifyOpts = sep argv [] [] -- accumulators...
387   where
388     sep :: [FAST_STRING]                         -- cmd-line opts (input)
389         -> [CoreToDo] -> [StgToDo]       -- to_do accumulators
390         -> ([CoreToDo], [StgToDo])       -- result
391
392     sep [] core_td stg_td -- all done!
393       = (reverse core_td, reverse stg_td)
394
395 #       define CORE_TD(to_do) sep opts (to_do:core_td) stg_td
396 #       define STG_TD(to_do)  sep opts core_td (to_do:stg_td)
397 #       define IGNORE_ARG()   sep opts core_td stg_td
398
399     sep (opt1:opts) core_td stg_td
400       =
401         case (_UNPK_ opt1) of -- the non-"just match a string" options are at the end...
402
403           ',' : _       -> IGNORE_ARG() -- it is for the parser
404
405           "-fsimplify"  -> -- gather up SimplifierSwitches specially...
406                            simpl_sep opts defaultSimplSwitches core_td stg_td
407
408           "-fcalc-inlinings1"-> CORE_TD(CoreDoCalcInlinings1)
409           "-fcalc-inlinings2"-> CORE_TD(CoreDoCalcInlinings2)
410           "-ffloat-inwards"  -> CORE_TD(CoreDoFloatInwards)
411           "-ffull-laziness"  -> CORE_TD(CoreDoFullLaziness)
412           "-fliberate-case"  -> CORE_TD(CoreLiberateCase)
413           "-fprint-core"     -> CORE_TD(CoreDoPrintCore)
414           "-fstatic-args"    -> CORE_TD(CoreDoStaticArgs)
415           "-fstrictness"     -> CORE_TD(CoreDoStrictness)
416           "-fspecialise"     -> CORE_TD(CoreDoSpecialising)
417           "-fdeforest"       -> CORE_TD(CoreDoDeforest)
418           "-ffoldr-build-worker-wrapper"  -> CORE_TD(CoreDoFoldrBuildWorkerWrapper)
419           "-ffoldr-build-ww-anal"  -> CORE_TD(CoreDoFoldrBuildWWAnal)
420
421           "-fstg-static-args" -> STG_TD(StgDoStaticArgs)
422           "-fupdate-analysis" -> STG_TD(StgDoUpdateAnalysis)
423           "-dstg-stats"       -> STG_TD(D_stg_stats)
424           "-flambda-lift"     -> STG_TD(StgDoLambdaLift)
425           "-fmassage-stg-for-profiling" -> STG_TD(StgDoMassageForProfiling)
426
427           _ -> -- NB: the driver is really supposed to handle bad options
428                IGNORE_ARG()
429
430     ----------------
431
432     simpl_sep :: [FAST_STRING]      -- cmd-line opts (input)
433         -> [SimplifierSwitch]       -- simplifier-switch accumulator
434         -> [CoreToDo] -> [StgToDo]  -- to_do accumulators
435         -> ([CoreToDo], [StgToDo])  -- result
436
437         -- "simpl_sep" tailcalls "sep" once it's seen one set
438         -- of SimplifierSwitches for a CoreDoSimplify.
439
440 #ifdef DEBUG
441     simpl_sep input@[] simpl_sw core_td stg_td
442       = panic "simpl_sep []"
443 #endif
444
445         -- The SimplifierSwitches should be delimited by "(" and ")".
446
447     simpl_sep (opt1:opts) simpl_sw core_td stg_td
448       = case (_UNPK_ opt1) of
449           "(" -> simpl_sep opts simpl_sw core_td stg_td
450           ")" -> let
451                     this_simpl = CoreDoSimplify (isAmongSimpl simpl_sw)
452                  in
453                  sep opts (this_simpl : core_td) stg_td
454
455 #         define SIMPL_SW(sw) simpl_sep opts (sw:simpl_sw) core_td stg_td
456
457           -- the non-"just match a string" options are at the end...
458           "-fshow-simplifier-progress"      -> SIMPL_SW(ShowSimplifierProgress)
459           "-fcode-duplication-ok"           -> SIMPL_SW(SimplOkToDupCode)
460           "-ffloat-lets-exposing-whnf"      -> SIMPL_SW(SimplFloatLetsExposingWHNF)
461           "-ffloat-primops-ok"              -> SIMPL_SW(SimplOkToFloatPrimOps)
462           "-falways-float-lets-from-lets"   -> SIMPL_SW(SimplAlwaysFloatLetsFromLets)
463           "-fdo-case-elim"                  -> SIMPL_SW(SimplDoCaseElim)
464           "-fdo-lambda-eta-expansion"       -> SIMPL_SW(SimplDoLambdaEtaExpansion)
465           "-fdo-foldr-build"                -> SIMPL_SW(SimplDoFoldrBuild)
466           "-fdo-not-fold-back-append"       -> SIMPL_SW(SimplDontFoldBackAppend)
467           "-fdo-arity-expand"               -> SIMPL_SW(SimplDoArityExpand)
468           "-fdo-inline-foldr-build"         -> SIMPL_SW(SimplDoInlineFoldrBuild)
469           "-freuse-con"                     -> SIMPL_SW(SimplReuseCon)
470           "-fcase-of-case"                  -> SIMPL_SW(SimplCaseOfCase)
471           "-fcase-merge"                    -> SIMPL_SW(SimplCaseMerge)
472           "-flet-to-case"                   -> SIMPL_SW(SimplLetToCase)
473           "-fpedantic-bottoms"              -> SIMPL_SW(SimplPedanticBottoms)
474           "-fkeep-spec-pragma-ids"          -> SIMPL_SW(KeepSpecPragmaIds)
475           "-fkeep-unused-bindings"          -> SIMPL_SW(KeepUnusedBindings)
476           "-fmay-delete-conjurable-ids"     -> SIMPL_SW(SimplMayDeleteConjurableIds)
477           "-fessential-unfoldings-only"     -> SIMPL_SW(EssentialUnfoldingsOnly)
478           "-fignore-inline-pragma"          -> SIMPL_SW(IgnoreINLINEPragma)
479           "-fno-let-from-case"              -> SIMPL_SW(SimplNoLetFromCase)
480           "-fno-let-from-app"               -> SIMPL_SW(SimplNoLetFromApp)
481           "-fno-let-from-strict-let"        -> SIMPL_SW(SimplNoLetFromStrictLet)
482
483           o | starts_with_msi  -> SIMPL_SW(MaxSimplifierIterations (read after_msi))
484            where
485             maybe_msi           = startsWith "-fmax-simplifier-iterations"   o
486             starts_with_msi     = maybeToBool maybe_msi
487             (Just after_msi)    = maybe_msi
488
489           _ -> -- NB: the driver is really supposed to handle bad options
490                simpl_sep opts simpl_sw core_td stg_td
491 \end{code}
492
493 %************************************************************************
494 %*                                                                      *
495 \subsection{Switch ordering}
496 %*                                                                      *
497 %************************************************************************
498
499 In spite of the @Produce*@ and @SccGroup@ constructors, these things
500 behave just like enumeration types.
501
502 \begin{code}
503 instance Eq SimplifierSwitch where
504     a == b = tagOf_SimplSwitch a _EQ_ tagOf_SimplSwitch b
505
506 instance Ord SimplifierSwitch where
507     a <  b  = tagOf_SimplSwitch a _LT_ tagOf_SimplSwitch b
508     a <= b  = tagOf_SimplSwitch a _LE_ tagOf_SimplSwitch b
509
510 tagOf_SimplSwitch SimplOkToDupCode              =(ILIT(0) :: FAST_INT)
511 tagOf_SimplSwitch SimplFloatLetsExposingWHNF    = ILIT(1)
512 tagOf_SimplSwitch SimplOkToFloatPrimOps         = ILIT(2)
513 tagOf_SimplSwitch SimplAlwaysFloatLetsFromLets  = ILIT(3)
514 tagOf_SimplSwitch SimplDoCaseElim               = ILIT(4)
515 tagOf_SimplSwitch SimplReuseCon                 = ILIT(5)
516 tagOf_SimplSwitch SimplCaseOfCase               = ILIT(6)
517 tagOf_SimplSwitch SimplLetToCase                = ILIT(7)
518 tagOf_SimplSwitch SimplMayDeleteConjurableIds   = ILIT(9)
519 tagOf_SimplSwitch SimplPedanticBottoms          = ILIT(10)
520 tagOf_SimplSwitch SimplDoArityExpand            = ILIT(11)
521 tagOf_SimplSwitch SimplDoFoldrBuild             = ILIT(12)
522 tagOf_SimplSwitch SimplDoInlineFoldrBuild       = ILIT(14)
523 tagOf_SimplSwitch IgnoreINLINEPragma            = ILIT(15)
524 tagOf_SimplSwitch SimplDoLambdaEtaExpansion     = ILIT(16)
525 tagOf_SimplSwitch EssentialUnfoldingsOnly       = ILIT(19)
526 tagOf_SimplSwitch ShowSimplifierProgress        = ILIT(20)
527 tagOf_SimplSwitch (MaxSimplifierIterations _)   = ILIT(21)
528 tagOf_SimplSwitch KeepSpecPragmaIds             = ILIT(25)
529 tagOf_SimplSwitch KeepUnusedBindings            = ILIT(26)
530 tagOf_SimplSwitch SimplNoLetFromCase            = ILIT(27)
531 tagOf_SimplSwitch SimplNoLetFromApp             = ILIT(28)
532 tagOf_SimplSwitch SimplNoLetFromStrictLet       = ILIT(29)
533 tagOf_SimplSwitch SimplDontFoldBackAppend       = ILIT(30)
534 tagOf_SimplSwitch SimplCaseMerge                = ILIT(31)
535 tagOf_SimplSwitch SimplCaseScrutinee            = ILIT(32)
536
537 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
538
539 tagOf_SimplSwitch _ = panic# "tagOf_SimplSwitch"
540
541 lAST_SIMPL_SWITCH_TAG = IBOX(tagOf_SimplSwitch SimplCaseScrutinee)
542 \end{code}
543
544 %************************************************************************
545 %*                                                                      *
546 \subsection{Switch lookup}
547 %*                                                                      *
548 %************************************************************************
549
550 \begin{code}
551 #if __GLASGOW_HASKELL__ == 201
552 # define ARRAY      Array
553 # define LIFT       GHCbase.Lift
554 # define SET_TO     =:
555 (=:) a b = (a,b)
556 #elif __GLASGOW_HASKELL__ >= 202
557 # define ARRAY      Array
558 # define LIFT       Lift
559 # define SET_TO     =:
560 (=:) a b = (a,b)
561 #else
562 # define ARRAY      _Array
563 # define LIFT       _Lift
564 # define SET_TO     :=
565 #endif
566
567 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
568
569 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
570                                         -- in the list; defaults right at the end.
571   = let
572         tidied_on_switches = foldl rm_dups [] on_switches
573                 -- The fold*l* ensures that we keep the latest switches;
574                 -- ie the ones that occur earliest in the list.
575
576         sw_tbl :: Array Int SwitchResult
577
578         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
579                         all_undefined)
580                  // defined_elems
581
582         all_undefined = [ i SET_TO SwBool False | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
583
584         defined_elems = map mk_assoc_elem tidied_on_switches
585     in
586     -- (avoid some unboxing, bounds checking, and other horrible things:)
587     case sw_tbl of { ARRAY bounds_who_needs_'em stuff ->
588     \ switch ->
589         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
590           LIFT v -> v
591     }
592   where
593     mk_assoc_elem k@(MaxSimplifierIterations lvl)       = IBOX(tagOf_SimplSwitch k) SET_TO SwInt lvl
594
595     mk_assoc_elem k = IBOX(tagOf_SimplSwitch k) SET_TO SwBool   True -- I'm here, Mom!
596
597     -- cannot have duplicates if we are going to use the array thing
598     rm_dups switches_so_far switch
599       = if switch `is_elem` switches_so_far
600         then switches_so_far
601         else switch : switches_so_far
602       where
603         sw `is_elem` []     = False
604         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) _EQ_ (tagOf_SimplSwitch s)
605                             || sw `is_elem` ss
606 \end{code}
607
608 Default settings for simplifier switches
609
610 \begin{code}
611 defaultSimplSwitches = [MaxSimplifierIterations         1
612                        ]
613 \end{code}
614
615 %************************************************************************
616 %*                                                                      *
617 \subsection{Misc functions for command-line options}
618 %*                                                                      *
619 %************************************************************************
620
621
622 \begin{code}
623 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
624
625 switchIsOn lookup_fn switch
626   = case (lookup_fn switch) of
627       SwBool False -> False
628       _            -> True
629
630 stringSwitchSet :: (switch -> SwitchResult)
631                 -> (FAST_STRING -> switch)
632                 -> Maybe FAST_STRING
633
634 stringSwitchSet lookup_fn switch
635   = case (lookup_fn (switch (panic "stringSwitchSet"))) of
636       SwString str -> Just str
637       _            -> Nothing
638
639 intSwitchSet :: (switch -> SwitchResult)
640              -> (Int -> switch)
641              -> Maybe Int
642
643 intSwitchSet lookup_fn switch
644   = case (lookup_fn (switch (panic "intSwitchSet"))) of
645       SwInt int -> Just int
646       _         -> Nothing
647 \end{code}