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