[project @ 1999-03-25 13:13:51 by simonm]
[ghc-hetmet.git] / ghc / compiler / main / CmdLineOpts.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1996-98
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         opt_AllStrict,
18         opt_AllowOverlappingInstances,
19         opt_AllowUndecidableInstances,
20         opt_AutoSccsOnAllToplevs,
21         opt_AutoSccsOnExportedToplevs,
22         opt_AutoSccsOnIndividualCafs,
23         opt_AutoSccsOnDicts,
24         opt_CompilingPrelude,
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_inlinings,
31         opt_D_dump_foreign,
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_show_rn_imports,
45         opt_D_simplifier_stats,
46         opt_D_source_stats,
47         opt_D_verbose_core2core,
48         opt_D_verbose_stg2stg,
49         opt_DictsStrict,
50         opt_DoCoreLinting,
51         opt_DoStgLinting,
52         opt_DoSemiTagging,
53         opt_DoEtaReduction,
54         opt_DoTickyProfiling,
55         opt_EmitCExternDecls,
56         opt_EnsureSplittableC,
57         opt_FoldrBuildOn,
58         opt_GlasgowExts,
59         opt_GranMacros,
60         opt_HiMap,
61         opt_HiVersion,
62         opt_IgnoreIfacePragmas,
63         opt_IrrefutableTuples,
64         opt_LiberateCaseThreshold,
65         opt_MaxContextReductionDepth,
66         opt_MultiParamClasses,
67         opt_NoHiCheck,
68         opt_NoImplicitPrelude,
69         opt_NoPreInlining,
70         opt_NumbersStrict,
71         opt_OmitBlackHoling,
72         opt_OmitInterfacePragmas,
73         opt_PprStyle_NoPrags,
74         opt_PprStyle_Debug,
75         opt_PprUserLength,
76         opt_ProduceC,
77         opt_ProduceHi,
78         opt_ProduceS,
79         opt_ProduceExportCStubs,
80         opt_ProduceExportHStubs,
81         opt_ReportCompile,
82         opt_SccGroup,
83         opt_SccProfilingOn,
84         opt_SourceUnchanged,
85         opt_Static,
86         opt_StgDoLetNoEscapes,
87         opt_Parallel,
88
89         opt_InterfaceUnfoldThreshold,
90         opt_UnfoldCasms,
91         opt_UnfoldingCreationThreshold,
92         opt_UnfoldingConDiscount,
93         opt_UnfoldingUseThreshold,
94         opt_UnfoldingKeenessFactor,
95
96         opt_Verbose,
97
98         opt_WarnNameShadowing,
99         opt_WarnUnusedMatches,
100         opt_WarnUnusedBinds,
101         opt_WarnUnusedImports,
102         opt_WarnIncompletePatterns,
103         opt_WarnOverlappingPatterns,
104         opt_WarnSimplePatterns,
105         opt_WarnTypeDefaults,
106         opt_WarnMissingMethods,
107         opt_WarnDuplicateExports,
108         opt_WarnHiShadows,
109         opt_WarnMissingSigs,
110         opt_PruneTyDecls, opt_PruneInstDecls,
111         opt_D_show_rn_stats
112     ) where
113
114 #include "HsVersions.h"
115
116 import Array    ( array, (//) )
117 import GlaExts
118 import Argv
119 import Constants        -- Default values for some flags
120
121 import Maybes           ( assocMaybe, firstJust, maybeToBool )
122 import Panic            ( panic, panic# )
123
124 #if __GLASGOW_HASKELL__ < 301
125 import ArrBase  ( Array(..) )
126 #else
127 import PrelArr  ( Array(..) )
128 #endif
129 \end{code}
130
131 A command-line {\em switch} is (generally) either on or off; e.g., the
132 ``verbose'' (-v) switch is either on or off.  (The \tr{-G<group>}
133 switch is an exception; it's set to a string, or nothing.)
134
135 A list of {\em ToDo}s is things to be done in a particular part of
136 processing.  A (fictitious) example for the Core-to-Core simplifier
137 might be: run the simplifier, then run the strictness analyser, then
138 run the simplifier again (three ``todos'').
139
140 There are three ``to-do processing centers'' at the moment.  In the
141 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
142 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
143 (\tr{simplStg/SimplStg.lhs}).
144
145 %************************************************************************
146 %*                                                                      *
147 \subsection{Datatypes associated with command-line options}
148 %*                                                                      *
149 %************************************************************************
150
151 \begin{code}
152 data SwitchResult
153   = SwBool      Bool            -- on/off
154   | SwString    FAST_STRING     -- nothing or a String
155   | SwInt       Int             -- nothing or an Int
156 \end{code}
157
158 \begin{code}
159 data CoreToDo           -- These are diff core-to-core passes,
160                         -- which may be invoked in any order,
161                         -- as many times as you like.
162
163   = CoreDoSimplify      -- The core-to-core simplifier.
164         (SimplifierSwitch -> SwitchResult)
165                         -- Each run of the simplifier can take a different
166                         -- set of simplifier-specific flags.
167   | CoreDoCalcInlinings1
168   | CoreDoCalcInlinings2
169   | CoreDoFloatInwards
170   | CoreDoFullLaziness
171   | CoreLiberateCase
172   | CoreDoPrintCore
173   | CoreDoStaticArgs
174   | CoreDoStrictness
175   | CoreDoSpecialising
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   | SimplCaseOfCase
199   | SimplLetToCase
200   | SimplMayDeleteConjurableIds
201   | SimplPedanticBottoms -- see Simplifier for an explanation
202   | SimplDoArityExpand   -- expand arity of bindings
203   | SimplDoFoldrBuild    -- This is the per-simplification flag;
204                          -- see also FoldrBuildOn, used elsewhere
205                          -- in the compiler.
206   | SimplDoInlineFoldrBuild
207                          -- inline foldr/build (*after* f/b rule is used)
208
209   | IgnoreINLINEPragma
210   | SimplDoLambdaEtaExpansion
211
212   | EssentialUnfoldingsOnly -- never mind the thresholds, only
213                             -- do unfoldings that *must* be done
214                             -- (to saturate constructors and primitives)
215
216   | MaxSimplifierIterations Int
217
218   | SimplNoLetFromCase      -- used when turning off floating entirely
219   | SimplNoLetFromApp       -- (for experimentation only) WDP 95/10
220   | SimplNoLetFromStrictLet
221
222   | SimplCaseMerge
223   | SimplPleaseClone
224 \end{code}
225
226 %************************************************************************
227 %*                                                                      *
228 \subsection{Classifying command-line options}
229 %*                                                                      *
230 %************************************************************************
231
232 \begin{code}
233 lookUp           :: FAST_STRING -> Bool
234 lookup_int       :: String -> Maybe Int
235 lookup_def_int   :: String -> Int -> Int
236 lookup_def_float :: String -> Float -> Float
237 lookup_str       :: String -> Maybe String
238
239 lookUp     sw = maybeToBool (assoc_opts sw)
240         
241 lookup_str sw = firstJust (map (startsWith sw) unpacked_opts)
242
243 lookup_int sw = case (lookup_str sw) of
244                   Nothing -> Nothing
245                   Just xx -> Just (read xx)
246
247 lookup_def_int sw def = case (lookup_str sw) of
248                             Nothing -> def              -- Use default
249                             Just xx -> read xx
250
251 lookup_def_float sw def = case (lookup_str sw) of
252                             Nothing -> def              -- Use default
253                             Just xx -> read xx
254
255 assoc_opts    = assocMaybe [ (a, True) | a <- argv ]
256 unpacked_opts = map _UNPK_ argv
257
258 {-
259  Putting the compiler options into temporary at-files
260  may turn out to be necessary later on if we turn hsc into
261  a pure Win32 application where I think there's a command-line
262  length limit of 255. unpacked_opts understands the @ option.
263
264 assoc_opts    = assocMaybe [ (_PK_ a, True) | a <- unpacked_opts ]
265
266 unpacked_opts :: [String]
267 unpacked_opts =
268   concat $
269   map (expandAts) $
270   map _UNPK_ argv
271   where
272    expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
273    expandAts l = [l]
274 -}
275 \end{code}
276
277 \begin{code}
278 opt_AllStrict                   = lookUp  SLIT("-fall-strict")
279 opt_AllowOverlappingInstances   = lookUp  SLIT("-fallow-overlapping-instances")
280 opt_AllowUndecidableInstances   = lookUp  SLIT("-fallow-undecidable-instances")
281 opt_AutoSccsOnAllToplevs        = lookUp  SLIT("-fauto-sccs-on-all-toplevs")
282 opt_AutoSccsOnExportedToplevs   = lookUp  SLIT("-fauto-sccs-on-exported-toplevs")
283 opt_AutoSccsOnIndividualCafs    = lookUp  SLIT("-fauto-sccs-on-individual-cafs")
284 opt_AutoSccsOnDicts             = lookUp  SLIT("-fauto-sccs-on-dicts")
285   {-
286    It's a bit unfortunate to have to re-introduce this chap, but on Win32
287    platforms we do need a way of distinguishing between the case when we're
288    compiling a static version of the Prelude and one that's going to be
289    put into a DLL. Why? Because the compiler's wired in modules need to
290    be attributed as either coming from a DLL or not.
291   -}
292 opt_CompilingPrelude            = lookUp  SLIT("-fcompiling-prelude")
293 opt_D_dump_absC                 = lookUp  SLIT("-ddump-absC")
294 opt_D_dump_asm                  = lookUp  SLIT("-ddump-asm")
295 opt_D_dump_deriv                = lookUp  SLIT("-ddump-deriv")
296 opt_D_dump_ds                   = lookUp  SLIT("-ddump-ds")
297 opt_D_dump_flatC                = lookUp  SLIT("-ddump-flatC")
298 opt_D_dump_inlinings            = lookUp  SLIT("-ddump-inlinings")
299 opt_D_dump_foreign              = lookUp  SLIT("-ddump-foreign-stubs")
300 opt_D_dump_occur_anal           = lookUp  SLIT("-ddump-occur-anal")
301 opt_D_dump_rdr                  = lookUp  SLIT("-ddump-rdr")
302 opt_D_dump_realC                = lookUp  SLIT("-ddump-realC")
303 opt_D_dump_rn                   = lookUp  SLIT("-ddump-rn")
304 opt_D_dump_simpl                = lookUp  SLIT("-ddump-simpl")
305 opt_D_dump_simpl_iterations     = lookUp  SLIT("-ddump-simpl-iterations")
306 opt_D_dump_spec                 = lookUp  SLIT("-ddump-spec")
307 opt_D_dump_stg                  = lookUp  SLIT("-ddump-stg")
308 opt_D_dump_stranal              = lookUp  SLIT("-ddump-stranal")
309 opt_D_dump_tc                   = lookUp  SLIT("-ddump-tc")
310 opt_D_show_passes               = lookUp  SLIT("-dshow-passes")
311 opt_D_show_rn_trace             = lookUp  SLIT("-dshow-rn-trace")
312 opt_D_show_rn_imports           = lookUp  SLIT("-dshow-rn-imports")
313 opt_D_simplifier_stats          = lookUp  SLIT("-dsimplifier-stats")
314 opt_D_source_stats              = lookUp  SLIT("-dsource-stats")
315 opt_D_verbose_core2core         = lookUp  SLIT("-dverbose-simpl")
316 opt_D_verbose_stg2stg           = lookUp  SLIT("-dverbose-stg")
317 opt_DictsStrict                 = lookUp  SLIT("-fdicts-strict")
318 opt_DoCoreLinting               = lookUp  SLIT("-dcore-lint")
319 opt_DoStgLinting                = lookUp  SLIT("-dstg-lint")
320 opt_DoEtaReduction              = lookUp  SLIT("-fdo-eta-reduction")
321 opt_DoSemiTagging               = lookUp  SLIT("-fsemi-tagging")
322 opt_DoTickyProfiling            = lookUp  SLIT("-fticky-ticky")
323 opt_EmitCExternDecls            = lookUp  SLIT("-femit-extern-decls")
324 opt_EnsureSplittableC           = lookUp  SLIT("-fglobalise-toplev-names")
325 opt_FoldrBuildOn                = lookUp  SLIT("-ffoldr-build-on")
326 opt_GranMacros                  = lookUp  SLIT("-fgransim")
327 opt_GlasgowExts                 = lookUp  SLIT("-fglasgow-exts")
328 opt_HiMap                       = lookup_str "-himap="       -- file saying where to look for .hi files
329 opt_HiVersion                   = lookup_def_int "-fhi-version=" 0 -- what version we're compiling.
330 opt_IgnoreIfacePragmas          = lookUp  SLIT("-fignore-interface-pragmas")
331 opt_IrrefutableTuples           = lookUp  SLIT("-firrefutable-tuples")
332 opt_MaxContextReductionDepth    = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
333 opt_MultiParamClasses           = opt_GlasgowExts
334 opt_NoHiCheck                   = lookUp  SLIT("-fno-hi-version-check")
335 opt_NoImplicitPrelude           = lookUp  SLIT("-fno-implicit-prelude")
336 opt_NoPreInlining               = lookUp  SLIT("-fno-pre-inlining")
337 opt_NumbersStrict               = lookUp  SLIT("-fnumbers-strict")
338 opt_OmitBlackHoling             = lookUp  SLIT("-dno-black-holing")
339 opt_OmitInterfacePragmas        = lookUp  SLIT("-fomit-interface-pragmas")
340 opt_PprStyle_NoPrags            = lookUp  SLIT("-dppr-noprags")
341 opt_PprStyle_Debug              = lookUp  SLIT("-dppr-debug")
342 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
343 opt_ProduceC                    = lookup_str "-C="
344 opt_ProduceS                    = lookup_str "-S="
345 opt_ProduceExportCStubs         = lookup_str "-F="
346 opt_ProduceExportHStubs         = lookup_str "-FH="
347 opt_ProduceHi                   = lookup_str "-hifile=" -- the one to produce this time 
348 opt_ReportCompile                = lookUp SLIT("-freport-compile")
349 opt_SccProfilingOn              = lookUp  SLIT("-fscc-profiling")
350 opt_SourceUnchanged             = lookUp  SLIT("-fsource-unchanged")
351 opt_StgDoLetNoEscapes           = lookUp  SLIT("-flet-no-escape")
352 opt_Parallel                    = lookUp  SLIT("-fparallel")
353 opt_Static                      = lookUp  SLIT("-static")
354 opt_SccGroup                    = lookup_str "-G="
355 opt_Verbose                     = lookUp  SLIT("-v")
356
357 opt_UnfoldCasms                 = lookUp SLIT("-funfold-casms-in-hi-file")
358 opt_InterfaceUnfoldThreshold    = lookup_def_int "-funfolding-interface-threshold" iNTERFACE_UNFOLD_THRESHOLD
359 opt_UnfoldingCreationThreshold  = lookup_def_int "-funfolding-creation-threshold"  uNFOLDING_CREATION_THRESHOLD
360 opt_UnfoldingUseThreshold       = lookup_def_int "-funfolding-use-threshold"       uNFOLDING_USE_THRESHOLD
361 opt_UnfoldingConDiscount        = lookup_def_int "-funfolding-con-discount"        uNFOLDING_CON_DISCOUNT_WEIGHT
362                         
363 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold"       lIBERATE_CASE_THRESHOLD
364 opt_UnfoldingKeenessFactor      = lookup_def_float "-funfolding-keeness-factor"    uNFOLDING_KEENESS_FACTOR
365 opt_WarnNameShadowing           = lookUp  SLIT("-fwarn-name-shadowing")
366 opt_WarnHiShadows               = lookUp  SLIT("-fwarn-hi-shadowing")
367 opt_WarnIncompletePatterns      = lookUp  SLIT("-fwarn-incomplete-patterns")
368 opt_WarnOverlappingPatterns     = lookUp  SLIT("-fwarn-overlapping-patterns")
369 opt_WarnSimplePatterns          = lookUp  SLIT("-fwarn-simple-patterns")
370 opt_WarnTypeDefaults            = lookUp  SLIT("-fwarn-type-defaults")
371 opt_WarnUnusedMatches           = lookUp  SLIT("-fwarn-unused-matches")
372 opt_WarnUnusedBinds             = lookUp  SLIT("-fwarn-unused-binds")
373 opt_WarnUnusedImports           = lookUp  SLIT("-fwarn-unused-imports")
374 opt_WarnMissingMethods          = lookUp  SLIT("-fwarn-missing-methods")
375 opt_WarnDuplicateExports        = lookUp  SLIT("-fwarn-duplicate-exports")
376 opt_WarnMissingSigs             = lookUp  SLIT("-fwarn-missing-signatures")
377 opt_PruneTyDecls                = not (lookUp SLIT("-fno-prune-tydecls"))
378 opt_PruneInstDecls              = not (lookUp SLIT("-fno-prune-instdecls"))
379 opt_D_show_rn_stats             = lookUp SLIT("-dshow-rn-stats")
380
381 -- opt_UnfoldingOverrideThreshold       = lookup_int "-funfolding-override-threshold"
382 \end{code}
383
384 \begin{code}
385 classifyOpts :: ([CoreToDo],    -- Core-to-Core processing spec
386                  [StgToDo])     -- STG-to-STG   processing spec
387
388 classifyOpts = sep argv [] [] -- accumulators...
389   where
390     sep :: [FAST_STRING]                 -- cmd-line opts (input)
391         -> [CoreToDo] -> [StgToDo]       -- to_do accumulators
392         -> ([CoreToDo], [StgToDo])       -- result
393
394     sep [] core_td stg_td -- all done!
395       = (reverse core_td, reverse stg_td)
396
397 #       define CORE_TD(to_do) sep opts (to_do:core_td) stg_td
398 #       define STG_TD(to_do)  sep opts core_td (to_do:stg_td)
399
400     sep (opt1:opts) core_td stg_td
401       = case (_UNPK_ opt1) of -- the non-"just match a string" options are at the end...
402           ',' : _       -> sep opts core_td stg_td -- it is for the parser
403
404           "-fsimplify"  -> -- gather up SimplifierSwitches specially...
405                            simpl_sep opts defaultSimplSwitches core_td stg_td
406
407           "-fcalc-inlinings1"-> CORE_TD(CoreDoCalcInlinings1)
408           "-fcalc-inlinings2"-> CORE_TD(CoreDoCalcInlinings2)
409           "-ffloat-inwards"  -> CORE_TD(CoreDoFloatInwards)
410           "-ffull-laziness"  -> CORE_TD(CoreDoFullLaziness)
411           "-fliberate-case"  -> CORE_TD(CoreLiberateCase)
412           "-fprint-core"     -> CORE_TD(CoreDoPrintCore)
413           "-fstatic-args"    -> CORE_TD(CoreDoStaticArgs)
414           "-fstrictness"     -> CORE_TD(CoreDoStrictness)
415           "-fspecialise"     -> CORE_TD(CoreDoSpecialising)
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                sep opts core_td stg_td
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           "-fcode-duplication-ok"           -> SIMPL_SW(SimplOkToDupCode)
457           "-ffloat-lets-exposing-whnf"      -> SIMPL_SW(SimplFloatLetsExposingWHNF)
458           "-ffloat-primops-ok"              -> SIMPL_SW(SimplOkToFloatPrimOps)
459           "-falways-float-lets-from-lets"   -> SIMPL_SW(SimplAlwaysFloatLetsFromLets)
460           "-fdo-case-elim"                  -> SIMPL_SW(SimplDoCaseElim)
461           "-fdo-lambda-eta-expansion"       -> SIMPL_SW(SimplDoLambdaEtaExpansion)
462           "-fdo-foldr-build"                -> SIMPL_SW(SimplDoFoldrBuild)
463           "-fdo-arity-expand"               -> SIMPL_SW(SimplDoArityExpand)
464           "-fdo-inline-foldr-build"         -> SIMPL_SW(SimplDoInlineFoldrBuild)
465           "-fcase-of-case"                  -> SIMPL_SW(SimplCaseOfCase)
466           "-fcase-merge"                    -> SIMPL_SW(SimplCaseMerge)
467           "-flet-to-case"                   -> SIMPL_SW(SimplLetToCase)
468           "-fpedantic-bottoms"              -> SIMPL_SW(SimplPedanticBottoms)
469           "-fmay-delete-conjurable-ids"     -> SIMPL_SW(SimplMayDeleteConjurableIds)
470           "-fessential-unfoldings-only"     -> SIMPL_SW(EssentialUnfoldingsOnly)
471           "-fignore-inline-pragma"          -> SIMPL_SW(IgnoreINLINEPragma)
472           "-fno-let-from-case"              -> SIMPL_SW(SimplNoLetFromCase)
473           "-fno-let-from-app"               -> SIMPL_SW(SimplNoLetFromApp)
474           "-fno-let-from-strict-let"        -> SIMPL_SW(SimplNoLetFromStrictLet)
475           "-fclone-binds"                   -> SIMPL_SW(SimplPleaseClone)
476
477           o | starts_with_msi  -> SIMPL_SW(MaxSimplifierIterations (read after_msi))
478            where
479             maybe_msi           = startsWith "-fmax-simplifier-iterations"   o
480             starts_with_msi     = maybeToBool maybe_msi
481             (Just after_msi)    = maybe_msi
482
483           _ -> -- NB: the driver is really supposed to handle bad options
484                simpl_sep opts simpl_sw core_td stg_td
485 \end{code}
486
487 %************************************************************************
488 %*                                                                      *
489 \subsection{Switch ordering}
490 %*                                                                      *
491 %************************************************************************
492
493 In spite of the @Produce*@ and @SccGroup@ constructors, these things
494 behave just like enumeration types.
495
496 \begin{code}
497 instance Eq SimplifierSwitch where
498     a == b = tagOf_SimplSwitch a _EQ_ tagOf_SimplSwitch b
499
500 instance Ord SimplifierSwitch where
501     a <  b  = tagOf_SimplSwitch a _LT_ tagOf_SimplSwitch b
502     a <= b  = tagOf_SimplSwitch a _LE_ tagOf_SimplSwitch b
503
504 tagOf_SimplSwitch SimplOkToDupCode              =(ILIT(0) :: FAST_INT)
505 tagOf_SimplSwitch SimplFloatLetsExposingWHNF    = ILIT(1)
506 tagOf_SimplSwitch SimplOkToFloatPrimOps         = ILIT(2)
507 tagOf_SimplSwitch SimplAlwaysFloatLetsFromLets  = ILIT(3)
508 tagOf_SimplSwitch SimplDoCaseElim               = ILIT(4)
509 tagOf_SimplSwitch SimplCaseOfCase               = ILIT(6)
510 tagOf_SimplSwitch SimplLetToCase                = ILIT(7)
511 tagOf_SimplSwitch SimplMayDeleteConjurableIds   = ILIT(9)
512 tagOf_SimplSwitch SimplPedanticBottoms          = ILIT(10)
513 tagOf_SimplSwitch SimplDoArityExpand            = ILIT(11)
514 tagOf_SimplSwitch SimplDoFoldrBuild             = ILIT(12)
515 tagOf_SimplSwitch SimplDoInlineFoldrBuild       = ILIT(14)
516 tagOf_SimplSwitch IgnoreINLINEPragma            = ILIT(15)
517 tagOf_SimplSwitch SimplDoLambdaEtaExpansion     = ILIT(16)
518 tagOf_SimplSwitch EssentialUnfoldingsOnly       = ILIT(19)
519 tagOf_SimplSwitch (MaxSimplifierIterations _)   = ILIT(21)
520 tagOf_SimplSwitch SimplNoLetFromCase            = ILIT(27)
521 tagOf_SimplSwitch SimplNoLetFromApp             = ILIT(28)
522 tagOf_SimplSwitch SimplNoLetFromStrictLet       = ILIT(29)
523 tagOf_SimplSwitch SimplCaseMerge                = ILIT(31)
524 tagOf_SimplSwitch SimplPleaseClone              = ILIT(32)
525
526 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
527
528 tagOf_SimplSwitch _ = panic# "tagOf_SimplSwitch"
529
530 lAST_SIMPL_SWITCH_TAG = IBOX(tagOf_SimplSwitch SimplPleaseClone)
531 \end{code}
532
533 %************************************************************************
534 %*                                                                      *
535 \subsection{Switch lookup}
536 %*                                                                      *
537 %************************************************************************
538
539 \begin{code}
540 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
541
542 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
543                                         -- in the list; defaults right at the end.
544   = let
545         tidied_on_switches = foldl rm_dups [] on_switches
546                 -- The fold*l* ensures that we keep the latest switches;
547                 -- ie the ones that occur earliest in the list.
548
549         sw_tbl :: Array Int SwitchResult
550
551         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
552                         all_undefined)
553                  // defined_elems
554
555         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
556
557         defined_elems = map mk_assoc_elem tidied_on_switches
558     in
559     -- (avoid some unboxing, bounds checking, and other horrible things:)
560     case sw_tbl of { Array bounds_who_needs_'em stuff ->
561     \ switch ->
562         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
563 #if __GLASGOW_HASKELL__ < 400
564           Lift v -> v
565 #else
566           (# _, v #) -> v
567 #endif
568     }
569   where
570     mk_assoc_elem k@(MaxSimplifierIterations lvl)       = (IBOX(tagOf_SimplSwitch k), SwInt lvl)
571
572     mk_assoc_elem k = (IBOX(tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
573
574     -- cannot have duplicates if we are going to use the array thing
575     rm_dups switches_so_far switch
576       = if switch `is_elem` switches_so_far
577         then switches_so_far
578         else switch : switches_so_far
579       where
580         sw `is_elem` []     = False
581         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) _EQ_ (tagOf_SimplSwitch s)
582                             || sw `is_elem` ss
583 \end{code}
584
585 Default settings for simplifier switches
586
587 \begin{code}
588 defaultSimplSwitches = [MaxSimplifierIterations         1
589                        ]
590 \end{code}
591
592 %************************************************************************
593 %*                                                                      *
594 \subsection{Misc functions for command-line options}
595 %*                                                                      *
596 %************************************************************************
597
598
599 \begin{code}
600 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
601
602 switchIsOn lookup_fn switch
603   = case (lookup_fn switch) of
604       SwBool False -> False
605       _            -> True
606
607 intSwitchSet :: (switch -> SwitchResult)
608              -> (Int -> switch)
609              -> Maybe Int
610
611 intSwitchSet lookup_fn switch
612   = case (lookup_fn (switch (panic "intSwitchSet"))) of
613       SwInt int -> Just int
614       _         -> Nothing
615 \end{code}
616
617 \begin{code}
618 startsWith, endsWith :: String -> String -> Maybe String
619
620 startsWith []     str = Just str
621 startsWith (c:cs) (s:ss)
622   = if c /= s then Nothing else startsWith cs ss
623 startsWith  _     []  = Nothing
624
625 endsWith cs ss
626   = case (startsWith (reverse cs) (reverse ss)) of
627       Nothing -> Nothing
628       Just rs -> Just (reverse rs)
629 \end{code}