[project @ 2000-03-24 17:49:29 by simonpj]
[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         src_filename,
18
19         -- debugging opts
20         opt_D_dump_absC,
21         opt_D_dump_asm,
22         opt_D_dump_cpranal,
23         opt_D_dump_cse,
24         opt_D_dump_deriv,
25         opt_D_dump_ds,
26         opt_D_dump_flatC,
27         opt_D_dump_foreign,
28         opt_D_dump_inlinings,
29         opt_D_dump_occur_anal,
30         opt_D_dump_parsed,
31         opt_D_dump_realC,
32         opt_D_dump_rn,
33         opt_D_dump_rules,
34         opt_D_dump_simpl,
35         opt_D_dump_simpl_iterations,
36         opt_D_dump_simpl_stats,
37         opt_D_dump_spec,
38         opt_D_dump_stg,
39         opt_D_dump_stranal,
40         opt_D_dump_tc,
41         opt_D_dump_usagesp,
42         opt_D_dump_worker_wrapper,
43         opt_D_show_passes,
44         opt_D_dump_rn_trace,
45         opt_D_dump_rn_stats,
46         opt_D_dump_stix,
47         opt_D_source_stats,
48         opt_D_verbose_core2core,
49         opt_D_verbose_stg2stg,
50         opt_DoCoreLinting,
51         opt_DoStgLinting,
52         opt_DoUSPLinting,
53         opt_PprStyle_Debug,
54         opt_PprStyle_NoPrags,
55         opt_PprUserLength,
56
57         -- warning opts
58         opt_WarnDuplicateExports,
59         opt_WarnHiShadows,
60         opt_WarnIncompletePatterns,
61         opt_WarnMissingFields,
62         opt_WarnMissingMethods,
63         opt_WarnMissingSigs,
64         opt_WarnNameShadowing,
65         opt_WarnOverlappingPatterns,
66         opt_WarnSimplePatterns,
67         opt_WarnTypeDefaults,
68         opt_WarnUnusedBinds,
69         opt_WarnUnusedImports,
70         opt_WarnUnusedMatches,
71         opt_WarnDeprecations,
72
73         -- profiling opts
74         opt_AutoSccsOnAllToplevs,
75         opt_AutoSccsOnExportedToplevs,
76         opt_AutoSccsOnIndividualCafs,
77         opt_AutoSccsOnDicts,
78         opt_SccProfilingOn,
79         opt_DoTickyProfiling,
80
81         -- language opts
82         opt_AllStrict,
83         opt_DictsStrict,
84         opt_MaxContextReductionDepth,
85         opt_AllowOverlappingInstances,
86         opt_AllowUndecidableInstances,
87         opt_GlasgowExts,
88         opt_IrrefutableTuples,
89         opt_NumbersStrict,
90         opt_Parallel,
91         opt_SMP,
92
93         -- optimisation opts
94         opt_DoEtaReduction,
95         opt_DoSemiTagging,
96         opt_FoldrBuildOn,
97         opt_LiberateCaseThreshold,
98         opt_StgDoLetNoEscapes,
99         opt_UnfoldCasms,
100         opt_UsageSPOn,
101         opt_UnboxStrictFields,
102         opt_SimplNoPreInlining,
103         opt_SimplDoEtaReduction,
104         opt_SimplDoLambdaEtaExpansion,
105         opt_SimplCaseOfCase,
106         opt_SimplCaseMerge,
107         opt_SimplPedanticBottoms,
108
109         -- Unfolding control
110         opt_UF_HiFileThreshold,
111         opt_UF_CreationThreshold,
112         opt_UF_UseThreshold,
113         opt_UF_ScrutConDiscount,
114         opt_UF_FunAppDiscount,
115         opt_UF_PrimArgDiscount,
116         opt_UF_KeenessFactor,
117         opt_UF_CheapOp,
118         opt_UF_DearOp,
119
120         -- misc opts
121         opt_CompilingPrelude,
122         opt_EmitCExternDecls,
123         opt_EnsureSplittableC,
124         opt_GranMacros,
125         opt_HiMap,
126         opt_HiMapSep,
127         opt_HiVersion,
128         opt_HistorySize,
129         opt_IgnoreAsserts,
130         opt_IgnoreIfacePragmas,
131         opt_NoHiCheck,
132         opt_NoImplicitPrelude,
133         opt_OmitBlackHoling,
134         opt_OmitInterfacePragmas,
135         opt_ProduceC,
136         opt_ProduceExportCStubs,
137         opt_ProduceExportHStubs,
138         opt_ProduceHi,
139         opt_ProduceS,
140         opt_NoPruneDecls,
141         opt_ReportCompile,
142         opt_SourceUnchanged,
143         opt_Static,
144         opt_Unregisterised,
145         opt_Verbose,
146
147         -- Code generation
148         opt_UseVanillaRegs,
149         opt_UseFloatRegs,
150         opt_UseDoubleRegs,
151         opt_UseLongRegs
152     ) where
153
154 #include "HsVersions.h"
155
156 import Array    ( array, (//) )
157 import GlaExts
158 import Argv
159 import Constants        -- Default values for some flags
160
161 import FastString       ( headFS )
162 import Maybes           ( assocMaybe, firstJust, maybeToBool )
163 import Panic            ( panic, panic# )
164
165 #if __GLASGOW_HASKELL__ < 301
166 import ArrBase  ( Array(..) )
167 #else
168 import PrelArr  ( Array(..) )
169 #endif
170 \end{code}
171
172 A command-line {\em switch} is (generally) either on or off; e.g., the
173 ``verbose'' (-v) switch is either on or off.
174
175 A list of {\em ToDo}s is things to be done in a particular part of
176 processing.  A (fictitious) example for the Core-to-Core simplifier
177 might be: run the simplifier, then run the strictness analyser, then
178 run the simplifier again (three ``todos'').
179
180 There are three ``to-do processing centers'' at the moment.  In the
181 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
182 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
183 (\tr{simplStg/SimplStg.lhs}).
184
185
186 %************************************************************************
187 %*                                                                      *
188 \subsection{Datatypes associated with command-line options}
189 %*                                                                      *
190 %************************************************************************
191
192 \begin{code}
193 data SwitchResult
194   = SwBool      Bool            -- on/off
195   | SwString    FAST_STRING     -- nothing or a String
196   | SwInt       Int             -- nothing or an Int
197 \end{code}
198
199 \begin{code}
200 data CoreToDo           -- These are diff core-to-core passes,
201                         -- which may be invoked in any order,
202                         -- as many times as you like.
203
204   = CoreDoSimplify      -- The core-to-core simplifier.
205         (SimplifierSwitch -> SwitchResult)
206                         -- Each run of the simplifier can take a different
207                         -- set of simplifier-specific flags.
208   | CoreDoFloatInwards
209   | CoreDoFloatOutwards Bool    -- True <=> float lambdas to top level
210   | CoreLiberateCase
211   | CoreDoPrintCore
212   | CoreDoStaticArgs
213   | CoreDoStrictness
214   | CoreDoWorkerWrapper
215   | CoreDoSpecialising
216   | CoreDoUSPInf
217   | CoreDoCPResult 
218   | CoreCSE
219 \end{code}
220
221 \begin{code}
222 data StgToDo
223   = StgDoStaticArgs
224   | StgDoUpdateAnalysis
225   | StgDoLambdaLift
226   | StgDoMassageForProfiling  -- should be (next to) last
227   -- There's also setStgVarInfo, but its absolute "lastness"
228   -- is so critical that it is hardwired in (no flag).
229   | D_stg_stats
230 \end{code}
231
232 \begin{code}
233 data SimplifierSwitch
234   = MaxSimplifierIterations Int
235   | SimplInlinePhase Int
236   | DontApplyRules
237   | NoCaseOfCase
238   | SimplLetToCase
239 \end{code}
240
241 %************************************************************************
242 %*                                                                      *
243 \subsection{Classifying command-line options}
244 %*                                                                      *
245 %************************************************************************
246
247 \begin{code}
248 lookUp           :: FAST_STRING -> Bool
249 lookup_int       :: String -> Maybe Int
250 lookup_def_int   :: String -> Int -> Int
251 lookup_def_float :: String -> Float -> Float
252 lookup_str       :: String -> Maybe String
253
254 lookUp     sw = maybeToBool (assoc_opts sw)
255         
256 lookup_str sw = firstJust (map (startsWith sw) unpacked_opts)
257
258 lookup_int sw = case (lookup_str sw) of
259                   Nothing -> Nothing
260                   Just xx -> Just (read xx)
261
262 lookup_def_int sw def = case (lookup_str sw) of
263                             Nothing -> def              -- Use default
264                             Just xx -> read xx
265
266 lookup_def_char sw def = case (lookup_str sw) of
267                             Just (xx:_) -> xx
268                             _           -> def          -- Use default
269
270 lookup_def_float sw def = case (lookup_str sw) of
271                             Nothing -> def              -- Use default
272                             Just xx -> read xx
273
274 assoc_opts    = assocMaybe [ (a, True) | a <- argv ]
275 unpacked_opts = map _UNPK_ argv
276
277 {-
278  Putting the compiler options into temporary at-files
279  may turn out to be necessary later on if we turn hsc into
280  a pure Win32 application where I think there's a command-line
281  length limit of 255. unpacked_opts understands the @ option.
282
283 assoc_opts    = assocMaybe [ (_PK_ a, True) | a <- unpacked_opts ]
284
285 unpacked_opts :: [String]
286 unpacked_opts =
287   concat $
288   map (expandAts) $
289   map _UNPK_ argv
290   where
291    expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
292    expandAts l = [l]
293 -}
294 \end{code}
295
296 \begin{code}
297 src_filename :: FAST_STRING
298 src_filename = case argv of
299                   filename : rest | headFS filename /= '-' -> filename
300                   otherwise -> panic "no filename"
301 \end{code}
302
303 \begin{code}
304 -- debugging opts
305 opt_D_dump_all   {- do not -}   = lookUp  SLIT("-ddump-all")
306 opt_D_dump_most  {- export -}   = opt_D_dump_all  || lookUp  SLIT("-ddump-most")
307
308 opt_D_dump_absC                 = opt_D_dump_all  || lookUp  SLIT("-ddump-absC")
309 opt_D_dump_asm                  = opt_D_dump_all  || lookUp  SLIT("-ddump-asm")
310 opt_D_dump_cpranal              = opt_D_dump_most || lookUp  SLIT("-ddump-cpranal")
311 opt_D_dump_deriv                = opt_D_dump_most || lookUp  SLIT("-ddump-deriv")
312 opt_D_dump_ds                   = opt_D_dump_most || lookUp  SLIT("-ddump-ds")
313 opt_D_dump_flatC                = opt_D_dump_all  || lookUp  SLIT("-ddump-flatC")
314 opt_D_dump_foreign              = opt_D_dump_most || lookUp  SLIT("-ddump-foreign-stubs")
315 opt_D_dump_inlinings            = opt_D_dump_all  || lookUp  SLIT("-ddump-inlinings")
316 opt_D_dump_occur_anal           = opt_D_dump_all  || lookUp  SLIT("-ddump-occur-anal")
317 opt_D_dump_parsed               = opt_D_dump_most || lookUp  SLIT("-ddump-parsed")
318 opt_D_dump_realC                = opt_D_dump_all  || lookUp  SLIT("-ddump-realC")
319 opt_D_dump_rn                   = opt_D_dump_most || lookUp  SLIT("-ddump-rn")
320 opt_D_dump_simpl                = opt_D_dump_most || lookUp  SLIT("-ddump-simpl")
321 opt_D_dump_simpl_iterations     = opt_D_dump_all  || lookUp  SLIT("-ddump-simpl-iterations")
322 opt_D_dump_spec                 = opt_D_dump_most || lookUp  SLIT("-ddump-spec")
323 opt_D_dump_stg                  = opt_D_dump_most || lookUp  SLIT("-ddump-stg")
324 opt_D_dump_stranal              = opt_D_dump_most || lookUp  SLIT("-ddump-stranal")
325 opt_D_dump_tc                   = opt_D_dump_most || lookUp  SLIT("-ddump-tc")
326 opt_D_dump_rules                = opt_D_dump_most || lookUp  SLIT("-ddump-rules")
327 opt_D_dump_usagesp              = opt_D_dump_most || lookUp  SLIT("-ddump-usagesp")
328 opt_D_dump_cse                  = opt_D_dump_most || lookUp  SLIT("-ddump-cse")
329 opt_D_dump_worker_wrapper       = opt_D_dump_most || lookUp  SLIT("-ddump-workwrap")
330 opt_D_show_passes               = opt_D_dump_most || lookUp  SLIT("-dshow-passes")
331 opt_D_dump_rn_trace             = opt_D_dump_all  || lookUp  SLIT("-ddump-rn-trace")
332 opt_D_dump_rn_stats             = opt_D_dump_most || lookUp  SLIT("-ddump-rn-stats")
333 opt_D_dump_stix                 = opt_D_dump_all  || lookUp  SLIT("-ddump-stix")
334 opt_D_dump_simpl_stats          = opt_D_dump_most || lookUp  SLIT("-ddump-simpl-stats")
335 opt_D_source_stats              = opt_D_dump_most || lookUp  SLIT("-dsource-stats")
336 opt_D_verbose_core2core         = opt_D_dump_all  || lookUp  SLIT("-dverbose-simpl")
337 opt_D_verbose_stg2stg           = opt_D_dump_all  || lookUp  SLIT("-dverbose-stg")
338
339 opt_DoCoreLinting               = lookUp  SLIT("-dcore-lint")
340 opt_DoStgLinting                = lookUp  SLIT("-dstg-lint")
341 opt_DoUSPLinting                = lookUp  SLIT("-dusagesp-lint")
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
346 -- warning opts
347 opt_WarnDuplicateExports        = lookUp  SLIT("-fwarn-duplicate-exports")
348 opt_WarnHiShadows               = lookUp  SLIT("-fwarn-hi-shadowing")
349 opt_WarnIncompletePatterns      = lookUp  SLIT("-fwarn-incomplete-patterns")
350 opt_WarnMissingFields           = lookUp  SLIT("-fwarn-missing-fields")
351 opt_WarnMissingMethods          = lookUp  SLIT("-fwarn-missing-methods")
352 opt_WarnMissingSigs             = lookUp  SLIT("-fwarn-missing-signatures")
353 opt_WarnNameShadowing           = lookUp  SLIT("-fwarn-name-shadowing")
354 opt_WarnOverlappingPatterns     = lookUp  SLIT("-fwarn-overlapping-patterns")
355 opt_WarnSimplePatterns          = lookUp  SLIT("-fwarn-simple-patterns")
356 opt_WarnTypeDefaults            = lookUp  SLIT("-fwarn-type-defaults")
357 opt_WarnUnusedBinds             = lookUp  SLIT("-fwarn-unused-binds")
358 opt_WarnUnusedImports           = lookUp  SLIT("-fwarn-unused-imports")
359 opt_WarnUnusedMatches           = lookUp  SLIT("-fwarn-unused-matches")
360 opt_WarnDeprecations            = lookUp  SLIT("-fwarn-deprecations")
361
362 -- profiling opts
363 opt_AutoSccsOnAllToplevs        = lookUp  SLIT("-fauto-sccs-on-all-toplevs")
364 opt_AutoSccsOnExportedToplevs   = lookUp  SLIT("-fauto-sccs-on-exported-toplevs")
365 opt_AutoSccsOnIndividualCafs    = lookUp  SLIT("-fauto-sccs-on-individual-cafs")
366 opt_AutoSccsOnDicts             = lookUp  SLIT("-fauto-sccs-on-dicts")
367 opt_SccProfilingOn              = lookUp  SLIT("-fscc-profiling")
368 opt_DoTickyProfiling            = lookUp  SLIT("-fticky-ticky")
369
370 -- language opts
371 opt_AllStrict                   = lookUp  SLIT("-fall-strict")
372 opt_DictsStrict                 = lookUp  SLIT("-fdicts-strict")
373 opt_AllowOverlappingInstances   = lookUp  SLIT("-fallow-overlapping-instances")
374 opt_AllowUndecidableInstances   = lookUp  SLIT("-fallow-undecidable-instances")
375 opt_GlasgowExts                 = lookUp  SLIT("-fglasgow-exts")
376 opt_IrrefutableTuples           = lookUp  SLIT("-firrefutable-tuples")
377 opt_MaxContextReductionDepth    = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
378 opt_NumbersStrict               = lookUp  SLIT("-fnumbers-strict")
379 opt_Parallel                    = lookUp  SLIT("-fparallel")
380 opt_SMP                         = lookUp  SLIT("-fsmp")
381
382 -- optimisation opts
383 opt_DoEtaReduction              = lookUp  SLIT("-fdo-eta-reduction")
384 opt_DoSemiTagging               = lookUp  SLIT("-fsemi-tagging")
385 opt_FoldrBuildOn                = lookUp  SLIT("-ffoldr-build-on")
386 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold" (10::Int)
387 opt_StgDoLetNoEscapes           = lookUp  SLIT("-flet-no-escape")
388 opt_UnfoldCasms                 = lookUp SLIT("-funfold-casms-in-hi-file")
389 opt_UsageSPOn                   = lookUp  SLIT("-fusagesp-on")
390 opt_UnboxStrictFields           = lookUp  SLIT("-funbox-strict-fields")
391
392   {-
393    It's a bit unfortunate to have to re-introduce this chap, but on Win32
394    platforms we do need a way of distinguishing between the case when we're
395    compiling a static version of the Prelude and one that's going to be
396    put into a DLL. Why? Because the compiler's wired in modules need to
397    be attributed as either coming from a DLL or not.
398   -}
399 opt_CompilingPrelude            = lookUp  SLIT("-fcompiling-prelude")
400 opt_EmitCExternDecls            = lookUp  SLIT("-femit-extern-decls")
401 opt_EnsureSplittableC           = lookUp  SLIT("-fglobalise-toplev-names")
402 opt_GranMacros                  = lookUp  SLIT("-fgransim")
403 opt_HiMap                       = lookup_str "-himap="       -- file saying where to look for .hi files
404 opt_HiMapSep                    = lookup_def_char "-himap-sep=" ':'
405 opt_HiVersion                   = lookup_def_int "-fhi-version=" 0 -- what version we're compiling.
406 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
407 opt_IgnoreAsserts               = lookUp  SLIT("-fignore-asserts")
408 opt_IgnoreIfacePragmas          = lookUp  SLIT("-fignore-interface-pragmas")
409 opt_NoHiCheck                   = lookUp  SLIT("-fno-hi-version-check")
410 opt_NoImplicitPrelude           = lookUp  SLIT("-fno-implicit-prelude")
411 opt_OmitBlackHoling             = lookUp  SLIT("-dno-black-holing")
412 opt_OmitInterfacePragmas        = lookUp  SLIT("-fomit-interface-pragmas")
413 opt_ProduceC                    = lookup_str "-C="
414 opt_ProduceExportCStubs         = lookup_str "-F="
415 opt_ProduceExportHStubs         = lookup_str "-FH="
416 opt_ProduceHi                   = lookup_str "-hifile=" -- the one to produce this time 
417
418 -- Simplifier switches
419 opt_SimplNoPreInlining          = lookUp SLIT("-fno-pre-inlining")
420         -- NoPreInlining is there just to see how bad things
421         -- get if you don't do it!
422 opt_SimplDoEtaReduction         = lookUp SLIT("-fdo-eta-reduction")
423 opt_SimplDoLambdaEtaExpansion   = lookUp SLIT("-fdo-lambda-eta-expansion")
424 opt_SimplCaseOfCase             = lookUp SLIT("-fcase-of-case")
425 opt_SimplCaseMerge              = lookUp SLIT("-fcase-merge")
426 opt_SimplPedanticBottoms        = lookUp SLIT("-fpedantic-bottoms")
427
428 -- Unfolding control
429 opt_UF_HiFileThreshold          = lookup_def_int "-funfolding-interface-threshold" (45::Int)
430 opt_UF_CreationThreshold        = lookup_def_int "-funfolding-creation-threshold"  (45::Int)
431 opt_UF_UseThreshold             = lookup_def_int "-funfolding-use-threshold"       (8::Int)     -- Discounts can be big
432 opt_UF_ScrutConDiscount         = lookup_def_int "-funfolding-con-discount"        (2::Int)
433 opt_UF_FunAppDiscount           = lookup_def_int "-funfolding-fun-discount"        (6::Int)     -- It's great to inline a fn
434 opt_UF_PrimArgDiscount          = lookup_def_int "-funfolding-prim-discount"       (1::Int)
435 opt_UF_KeenessFactor            = lookup_def_float "-funfolding-keeness-factor"    (1.5::Float)
436
437 opt_UF_CheapOp  = ( 1 :: Int)   -- Only one instruction; and the args are charged for
438 opt_UF_DearOp   = ( 4 :: Int)
439                         
440 opt_ProduceS                    = lookup_str "-S="
441 opt_ReportCompile               = lookUp SLIT("-freport-compile")
442 opt_NoPruneDecls                = lookUp SLIT("-fno-prune-decls")
443 opt_SourceUnchanged             = lookUp SLIT("-fsource-unchanged")
444 opt_Static                      = lookUp SLIT("-static")
445 opt_Unregisterised              = lookUp SLIT("-funregisterised")
446 opt_Verbose                     = lookUp SLIT("-v")
447
448 opt_UseVanillaRegs | opt_Unregisterised = 0
449                    | otherwise          = mAX_Real_Vanilla_REG
450 opt_UseFloatRegs   | opt_Unregisterised = 0
451                    | otherwise          = mAX_Real_Float_REG
452 opt_UseDoubleRegs  | opt_Unregisterised = 0
453                    | otherwise          = mAX_Real_Double_REG
454 opt_UseLongRegs    | opt_Unregisterised = 0
455                    | otherwise          = mAX_Real_Long_REG
456 \end{code}
457
458 \begin{code}
459 classifyOpts :: ([CoreToDo],    -- Core-to-Core processing spec
460                  [StgToDo])     -- STG-to-STG   processing spec
461
462 classifyOpts = sep argv [] [] -- accumulators...
463   where
464     sep :: [FAST_STRING]                 -- cmd-line opts (input)
465         -> [CoreToDo] -> [StgToDo]       -- to_do accumulators
466         -> ([CoreToDo], [StgToDo])       -- result
467
468     sep [] core_td stg_td -- all done!
469       = (reverse core_td, reverse stg_td)
470
471 #       define CORE_TD(to_do) sep opts (to_do:core_td) stg_td
472 #       define STG_TD(to_do)  sep opts core_td (to_do:stg_td)
473
474     sep (opt1:opts) core_td stg_td
475       = case (_UNPK_ opt1) of -- the non-"just match a string" options are at the end...
476           ',' : _       -> sep opts core_td stg_td -- it is for the parser
477
478           "-fsimplify"  -> -- gather up SimplifierSwitches specially...
479                            simpl_sep opts defaultSimplSwitches core_td stg_td
480
481           "-ffloat-inwards"  -> CORE_TD(CoreDoFloatInwards)
482           "-ffloat-outwards"      -> CORE_TD(CoreDoFloatOutwards False)
483           "-ffloat-outwards-full" -> CORE_TD(CoreDoFloatOutwards True)
484           "-fliberate-case"  -> CORE_TD(CoreLiberateCase)
485           "-fcse"            -> CORE_TD(CoreCSE)
486           "-fprint-core"     -> CORE_TD(CoreDoPrintCore)
487           "-fstatic-args"    -> CORE_TD(CoreDoStaticArgs)
488           "-fstrictness"     -> CORE_TD(CoreDoStrictness)
489           "-fworker-wrapper" -> CORE_TD(CoreDoWorkerWrapper)
490           "-fspecialise"     -> CORE_TD(CoreDoSpecialising)
491           "-fusagesp"        -> CORE_TD(CoreDoUSPInf)
492           "-fcpr-analyse"    -> CORE_TD(CoreDoCPResult)
493
494           "-fstg-static-args" -> STG_TD(StgDoStaticArgs)
495           "-fupdate-analysis" -> STG_TD(StgDoUpdateAnalysis)
496           "-dstg-stats"       -> STG_TD(D_stg_stats)
497           "-flambda-lift"     -> STG_TD(StgDoLambdaLift)
498           "-fmassage-stg-for-profiling" -> STG_TD(StgDoMassageForProfiling)
499
500           _ -> -- NB: the driver is really supposed to handle bad options
501                sep opts core_td stg_td
502
503     ----------------
504
505     simpl_sep :: [FAST_STRING]            -- cmd-line opts (input)
506               -> [SimplifierSwitch]       -- simplifier-switch accumulator
507               -> [CoreToDo] -> [StgToDo]  -- to_do accumulators
508               -> ([CoreToDo], [StgToDo])  -- result
509
510         -- "simpl_sep" tailcalls "sep" once it's seen one set
511         -- of SimplifierSwitches for a CoreDoSimplify.
512
513 #ifdef DEBUG
514     simpl_sep input@[] simpl_sw core_td stg_td
515       = panic "simpl_sep []"
516 #endif
517
518         -- The SimplifierSwitches should be delimited by "[" and "]".
519
520     simpl_sep (opt1:opts) simpl_sw core_td stg_td
521       = case (_UNPK_ opt1) of
522           "[" -> simpl_sep opts simpl_sw core_td stg_td
523           "]" -> let
524                     this_simpl = CoreDoSimplify (isAmongSimpl simpl_sw)
525                  in
526                  sep opts (this_simpl : core_td) stg_td
527
528           opt -> case matchSimplSw opt of
529                         Just sw -> simpl_sep opts (sw:simpl_sw) core_td stg_td
530                         Nothing -> simpl_sep opts simpl_sw      core_td stg_td
531
532 matchSimplSw opt
533   = firstJust   [ matchSwInt  opt "-fmax-simplifier-iterations"         MaxSimplifierIterations
534                 , matchSwInt  opt "-finline-phase"                      SimplInlinePhase
535                 , matchSwBool opt "-fno-rules"                          DontApplyRules
536                 , matchSwBool opt "-fno-case-of-case"                   NoCaseOfCase
537                 , matchSwBool opt "-flet-to-case"                       SimplLetToCase
538                 ]
539
540 matchSwBool :: String -> String -> a -> Maybe a
541 matchSwBool opt str sw | opt == str = Just sw
542                        | otherwise  = Nothing
543
544 matchSwInt :: String -> String -> (Int -> a) -> Maybe a
545 matchSwInt opt str sw = case startsWith str opt of
546                             Just opt_left -> Just (sw (read opt_left))
547                             Nothing       -> Nothing
548 \end{code}
549
550 %************************************************************************
551 %*                                                                      *
552 \subsection{Switch ordering}
553 %*                                                                      *
554 %************************************************************************
555
556 In spite of the @Produce*@ constructor, these things behave just like
557 enumeration types.
558
559 \begin{code}
560 instance Eq SimplifierSwitch where
561     a == b = tagOf_SimplSwitch a _EQ_ tagOf_SimplSwitch b
562
563 instance Ord SimplifierSwitch where
564     a <  b  = tagOf_SimplSwitch a _LT_ tagOf_SimplSwitch b
565     a <= b  = tagOf_SimplSwitch a _LE_ tagOf_SimplSwitch b
566
567
568 tagOf_SimplSwitch (SimplInlinePhase _)          = ILIT(1)
569 tagOf_SimplSwitch (MaxSimplifierIterations _)   = ILIT(2)
570 tagOf_SimplSwitch DontApplyRules                = ILIT(3)
571 tagOf_SimplSwitch SimplLetToCase                = ILIT(4)
572 tagOf_SimplSwitch NoCaseOfCase                  = ILIT(5)
573
574 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
575
576 lAST_SIMPL_SWITCH_TAG = 5
577 \end{code}
578
579 %************************************************************************
580 %*                                                                      *
581 \subsection{Switch lookup}
582 %*                                                                      *
583 %************************************************************************
584
585 \begin{code}
586 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
587
588 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
589                                         -- in the list; defaults right at the end.
590   = let
591         tidied_on_switches = foldl rm_dups [] on_switches
592                 -- The fold*l* ensures that we keep the latest switches;
593                 -- ie the ones that occur earliest in the list.
594
595         sw_tbl :: Array Int SwitchResult
596         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
597                         all_undefined)
598                  // defined_elems
599
600         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
601
602         defined_elems = map mk_assoc_elem tidied_on_switches
603     in
604     -- (avoid some unboxing, bounds checking, and other horrible things:)
605 #if __GLASGOW_HASKELL__ < 405
606     case sw_tbl of { Array bounds_who_needs_'em stuff ->
607 #else
608     case sw_tbl of { Array _ _ stuff ->
609 #endif
610     \ switch ->
611         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
612 #if __GLASGOW_HASKELL__ < 400
613           Lift v -> v
614 #elif __GLASGOW_HASKELL__ < 403
615           (# _, v #) -> v
616 #else
617           (# v #) -> v
618 #endif
619     }
620   where
621     mk_assoc_elem k@(MaxSimplifierIterations lvl) = (IBOX(tagOf_SimplSwitch k), SwInt lvl)
622     mk_assoc_elem k@(SimplInlinePhase n)          = (IBOX(tagOf_SimplSwitch k), SwInt n)
623     mk_assoc_elem k                               = (IBOX(tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
624
625     -- cannot have duplicates if we are going to use the array thing
626     rm_dups switches_so_far switch
627       = if switch `is_elem` switches_so_far
628         then switches_so_far
629         else switch : switches_so_far
630       where
631         sw `is_elem` []     = False
632         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) _EQ_ (tagOf_SimplSwitch s)
633                             || sw `is_elem` ss
634 \end{code}
635
636 Default settings for simplifier switches
637
638 \begin{code}
639 defaultSimplSwitches = [MaxSimplifierIterations 1]
640 \end{code}
641
642 %************************************************************************
643 %*                                                                      *
644 \subsection{Misc functions for command-line options}
645 %*                                                                      *
646 %************************************************************************
647
648
649 \begin{code}
650 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
651
652 switchIsOn lookup_fn switch
653   = case (lookup_fn switch) of
654       SwBool False -> False
655       _            -> True
656
657 intSwitchSet :: (switch -> SwitchResult)
658              -> (Int -> switch)
659              -> Maybe Int
660
661 intSwitchSet lookup_fn switch
662   = case (lookup_fn (switch (panic "intSwitchSet"))) of
663       SwInt int -> Just int
664       _         -> Nothing
665 \end{code}
666
667 \begin{code}
668 startsWith :: String -> String -> Maybe String
669 -- startsWith pfx (pfx++rest) = Just rest
670
671 startsWith []     str = Just str
672 startsWith (c:cs) (s:ss)
673   = if c /= s then Nothing else startsWith cs ss
674 startsWith  _     []  = Nothing
675
676 endsWith  :: String -> String -> Maybe String
677 endsWith cs ss
678   = case (startsWith (reverse cs) (reverse ss)) of
679       Nothing -> Nothing
680       Just rs -> Just (reverse rs)
681 \end{code}