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