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