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