[project @ 2000-04-13 11:56:35 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_dump_minimal_imports,
48         opt_D_source_stats,
49         opt_D_verbose_core2core,
50         opt_D_verbose_stg2stg,
51         opt_DoCoreLinting,
52         opt_DoStgLinting,
53         opt_DoUSPLinting,
54         opt_PprStyle_Debug,
55         opt_PprStyle_NoPrags,
56         opt_PprUserLength,
57
58         -- warning opts
59         opt_WarnDuplicateExports,
60         opt_WarnHiShadows,
61         opt_WarnIncompletePatterns,
62         opt_WarnMissingFields,
63         opt_WarnMissingMethods,
64         opt_WarnMissingSigs,
65         opt_WarnNameShadowing,
66         opt_WarnOverlappingPatterns,
67         opt_WarnSimplePatterns,
68         opt_WarnTypeDefaults,
69         opt_WarnUnusedBinds,
70         opt_WarnUnusedImports,
71         opt_WarnUnusedMatches,
72         opt_WarnDeprecations,
73
74         -- profiling opts
75         opt_AutoSccsOnAllToplevs,
76         opt_AutoSccsOnExportedToplevs,
77         opt_AutoSccsOnIndividualCafs,
78         opt_AutoSccsOnDicts,
79         opt_SccProfilingOn,
80         opt_DoTickyProfiling,
81
82         -- language opts
83         opt_AllStrict,
84         opt_DictsStrict,
85         opt_MaxContextReductionDepth,
86         opt_AllowOverlappingInstances,
87         opt_AllowUndecidableInstances,
88         opt_GlasgowExts,
89         opt_IrrefutableTuples,
90         opt_NumbersStrict,
91         opt_Parallel,
92         opt_SMP,
93
94         -- optimisation opts
95         opt_DoEtaReduction,
96         opt_DoSemiTagging,
97         opt_FoldrBuildOn,
98         opt_LiberateCaseThreshold,
99         opt_StgDoLetNoEscapes,
100         opt_UnfoldCasms,
101         opt_UsageSPOn,
102         opt_UnboxStrictFields,
103         opt_SimplNoPreInlining,
104         opt_SimplDoEtaReduction,
105         opt_SimplDoLambdaEtaExpansion,
106         opt_SimplCaseOfCase,
107         opt_SimplCaseMerge,
108         opt_SimplPedanticBottoms,
109
110         -- Unfolding control
111         opt_UF_HiFileThreshold,
112         opt_UF_CreationThreshold,
113         opt_UF_UseThreshold,
114         opt_UF_ScrutConDiscount,
115         opt_UF_FunAppDiscount,
116         opt_UF_PrimArgDiscount,
117         opt_UF_KeenessFactor,
118         opt_UF_CheapOp,
119         opt_UF_DearOp,
120
121         -- misc opts
122         opt_InPackage,
123         opt_EmitCExternDecls,
124         opt_EnsureSplittableC,
125         opt_GranMacros,
126         opt_HiMap,
127         opt_HiMapSep,
128         opt_HiVersion,
129         opt_HistorySize,
130         opt_IgnoreAsserts,
131         opt_IgnoreIfacePragmas,
132         opt_NoHiCheck,
133         opt_NoImplicitPrelude,
134         opt_OmitBlackHoling,
135         opt_OmitInterfacePragmas,
136         opt_ProduceC,
137         opt_ProduceExportCStubs,
138         opt_ProduceExportHStubs,
139         opt_ProduceHi,
140         opt_ProduceS,
141         opt_NoPruneDecls,
142         opt_ReportCompile,
143         opt_SourceUnchanged,
144         opt_Static,
145         opt_Unregisterised,
146         opt_Verbose,
147
148         -- Code generation
149         opt_UseVanillaRegs,
150         opt_UseFloatRegs,
151         opt_UseDoubleRegs,
152         opt_UseLongRegs
153     ) where
154
155 #include "HsVersions.h"
156
157 import Array    ( array, (//) )
158 import GlaExts
159 import Argv
160 import Constants        -- Default values for some flags
161
162 import FastString       ( headFS )
163 import Maybes           ( assocMaybe, firstJust, maybeToBool )
164 import Panic            ( panic, panic# )
165
166 #if __GLASGOW_HASKELL__ < 301
167 import ArrBase  ( Array(..) )
168 #else
169 import PrelArr  ( Array(..) )
170 #endif
171 \end{code}
172
173 A command-line {\em switch} is (generally) either on or off; e.g., the
174 ``verbose'' (-v) switch is either on or off.
175
176 A list of {\em ToDo}s is things to be done in a particular part of
177 processing.  A (fictitious) example for the Core-to-Core simplifier
178 might be: run the simplifier, then run the strictness analyser, then
179 run the simplifier again (three ``todos'').
180
181 There are three ``to-do processing centers'' at the moment.  In the
182 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
183 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
184 (\tr{simplStg/SimplStg.lhs}).
185
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection{Datatypes associated with command-line options}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 data SwitchResult
195   = SwBool      Bool            -- on/off
196   | SwString    FAST_STRING     -- nothing or a String
197   | SwInt       Int             -- nothing or an Int
198 \end{code}
199
200 \begin{code}
201 data CoreToDo           -- These are diff core-to-core passes,
202                         -- which may be invoked in any order,
203                         -- as many times as you like.
204
205   = CoreDoSimplify      -- The core-to-core simplifier.
206         (SimplifierSwitch -> SwitchResult)
207                         -- Each run of the simplifier can take a different
208                         -- set of simplifier-specific flags.
209   | CoreDoFloatInwards
210   | CoreDoFloatOutwards Bool    -- True <=> float lambdas to top level
211   | CoreLiberateCase
212   | CoreDoPrintCore
213   | CoreDoStaticArgs
214   | CoreDoStrictness
215   | CoreDoWorkerWrapper
216   | CoreDoSpecialising
217   | CoreDoUSPInf
218   | CoreDoCPResult 
219   | CoreCSE
220 \end{code}
221
222 \begin{code}
223 data StgToDo
224   = StgDoStaticArgs
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 opt_D_dump_minimal_imports      = lookUp  SLIT("-ddump-minimal-imports")
339
340 opt_DoCoreLinting               = lookUp  SLIT("-dcore-lint")
341 opt_DoStgLinting                = lookUp  SLIT("-dstg-lint")
342 opt_DoUSPLinting                = lookUp  SLIT("-dusagesp-lint")
343 opt_PprStyle_NoPrags            = lookUp  SLIT("-dppr-noprags")
344 opt_PprStyle_Debug              = lookUp  SLIT("-dppr-debug")
345 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
346
347 -- warning opts
348 opt_WarnDuplicateExports        = lookUp  SLIT("-fwarn-duplicate-exports")
349 opt_WarnHiShadows               = lookUp  SLIT("-fwarn-hi-shadowing")
350 opt_WarnIncompletePatterns      = lookUp  SLIT("-fwarn-incomplete-patterns")
351 opt_WarnMissingFields           = lookUp  SLIT("-fwarn-missing-fields")
352 opt_WarnMissingMethods          = lookUp  SLIT("-fwarn-missing-methods")
353 opt_WarnMissingSigs             = lookUp  SLIT("-fwarn-missing-signatures")
354 opt_WarnNameShadowing           = lookUp  SLIT("-fwarn-name-shadowing")
355 opt_WarnOverlappingPatterns     = lookUp  SLIT("-fwarn-overlapping-patterns")
356 opt_WarnSimplePatterns          = lookUp  SLIT("-fwarn-simple-patterns")
357 opt_WarnTypeDefaults            = lookUp  SLIT("-fwarn-type-defaults")
358 opt_WarnUnusedBinds             = lookUp  SLIT("-fwarn-unused-binds")
359 opt_WarnUnusedImports           = lookUp  SLIT("-fwarn-unused-imports")
360 opt_WarnUnusedMatches           = lookUp  SLIT("-fwarn-unused-matches")
361 opt_WarnDeprecations            = lookUp  SLIT("-fwarn-deprecations")
362
363 -- profiling opts
364 opt_AutoSccsOnAllToplevs        = lookUp  SLIT("-fauto-sccs-on-all-toplevs")
365 opt_AutoSccsOnExportedToplevs   = lookUp  SLIT("-fauto-sccs-on-exported-toplevs")
366 opt_AutoSccsOnIndividualCafs    = lookUp  SLIT("-fauto-sccs-on-individual-cafs")
367 opt_AutoSccsOnDicts             = lookUp  SLIT("-fauto-sccs-on-dicts")
368 opt_SccProfilingOn              = lookUp  SLIT("-fscc-profiling")
369 opt_DoTickyProfiling            = lookUp  SLIT("-fticky-ticky")
370
371 -- language opts
372 opt_AllStrict                   = lookUp  SLIT("-fall-strict")
373 opt_DictsStrict                 = lookUp  SLIT("-fdicts-strict")
374 opt_AllowOverlappingInstances   = lookUp  SLIT("-fallow-overlapping-instances")
375 opt_AllowUndecidableInstances   = lookUp  SLIT("-fallow-undecidable-instances")
376 opt_GlasgowExts                 = lookUp  SLIT("-fglasgow-exts")
377 opt_IrrefutableTuples           = lookUp  SLIT("-firrefutable-tuples")
378 opt_MaxContextReductionDepth    = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
379 opt_NumbersStrict               = lookUp  SLIT("-fnumbers-strict")
380 opt_Parallel                    = lookUp  SLIT("-fparallel")
381 opt_SMP                         = lookUp  SLIT("-fsmp")
382
383 -- optimisation opts
384 opt_DoEtaReduction              = lookUp  SLIT("-fdo-eta-reduction")
385 opt_DoSemiTagging               = lookUp  SLIT("-fsemi-tagging")
386 opt_FoldrBuildOn                = lookUp  SLIT("-ffoldr-build-on")
387 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold" (10::Int)
388 opt_StgDoLetNoEscapes           = lookUp  SLIT("-flet-no-escape")
389 opt_UnfoldCasms                 = lookUp SLIT("-funfold-casms-in-hi-file")
390 opt_UsageSPOn                   = lookUp  SLIT("-fusagesp-on")
391 opt_UnboxStrictFields           = lookUp  SLIT("-funbox-strict-fields")
392
393 {-
394    The optional '-inpackage=P' flag tells what package 
395    we are compiling this module for.
396    The Prelude, for example is compiled with '-package prelude'
397 -}
398 opt_InPackage                   = case lookup_str "-inpackage=" of
399                                     Just p  -> _PK_ p
400                                     Nothing -> SLIT("Main")     -- The package name if none is specified
401
402 opt_EmitCExternDecls            = lookUp  SLIT("-femit-extern-decls")
403 opt_EnsureSplittableC           = lookUp  SLIT("-fglobalise-toplev-names")
404 opt_GranMacros                  = lookUp  SLIT("-fgransim")
405 opt_HiMap                       = lookup_str "-himap="       -- file saying where to look for .hi files
406 opt_HiMapSep                    = lookup_def_char "-himap-sep=" ':'
407 opt_HiVersion                   = lookup_def_int "-fhi-version=" 0 -- what version we're compiling.
408 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
409 opt_IgnoreAsserts               = lookUp  SLIT("-fignore-asserts")
410 opt_IgnoreIfacePragmas          = lookUp  SLIT("-fignore-interface-pragmas")
411 opt_NoHiCheck                   = lookUp  SLIT("-fno-hi-version-check")
412 opt_NoImplicitPrelude           = lookUp  SLIT("-fno-implicit-prelude")
413 opt_OmitBlackHoling             = lookUp  SLIT("-dno-black-holing")
414 opt_OmitInterfacePragmas        = lookUp  SLIT("-fomit-interface-pragmas")
415 opt_ProduceC                    = lookup_str "-C="
416 opt_ProduceExportCStubs         = lookup_str "-F="
417 opt_ProduceExportHStubs         = lookup_str "-FH="
418 opt_ProduceHi                   = lookup_str "-hifile=" -- the one to produce this time 
419
420 -- Simplifier switches
421 opt_SimplNoPreInlining          = lookUp SLIT("-fno-pre-inlining")
422         -- NoPreInlining is there just to see how bad things
423         -- get if you don't do it!
424 opt_SimplDoEtaReduction         = lookUp SLIT("-fdo-eta-reduction")
425 opt_SimplDoLambdaEtaExpansion   = lookUp SLIT("-fdo-lambda-eta-expansion")
426 opt_SimplCaseOfCase             = lookUp SLIT("-fcase-of-case")
427 opt_SimplCaseMerge              = lookUp SLIT("-fcase-merge")
428 opt_SimplPedanticBottoms        = lookUp SLIT("-fpedantic-bottoms")
429
430 -- Unfolding control
431 opt_UF_HiFileThreshold          = lookup_def_int "-funfolding-interface-threshold" (45::Int)
432 opt_UF_CreationThreshold        = lookup_def_int "-funfolding-creation-threshold"  (45::Int)
433 opt_UF_UseThreshold             = lookup_def_int "-funfolding-use-threshold"       (8::Int)     -- Discounts can be big
434 opt_UF_ScrutConDiscount         = lookup_def_int "-funfolding-con-discount"        (2::Int)
435 opt_UF_FunAppDiscount           = lookup_def_int "-funfolding-fun-discount"        (6::Int)     -- It's great to inline a fn
436 opt_UF_PrimArgDiscount          = lookup_def_int "-funfolding-prim-discount"       (1::Int)
437 opt_UF_KeenessFactor            = lookup_def_float "-funfolding-keeness-factor"    (1.5::Float)
438
439 opt_UF_CheapOp  = ( 1 :: Int)   -- Only one instruction; and the args are charged for
440 opt_UF_DearOp   = ( 4 :: Int)
441                         
442 opt_ProduceS                    = lookup_str "-S="
443 opt_ReportCompile               = lookUp SLIT("-freport-compile")
444 opt_NoPruneDecls                = lookUp SLIT("-fno-prune-decls")
445 opt_SourceUnchanged             = lookUp SLIT("-fsource-unchanged")
446 opt_Static                      = lookUp SLIT("-static")
447 opt_Unregisterised              = lookUp SLIT("-funregisterised")
448 opt_Verbose                     = lookUp SLIT("-v")
449
450 opt_UseVanillaRegs | opt_Unregisterised = 0
451                    | otherwise          = mAX_Real_Vanilla_REG
452 opt_UseFloatRegs   | opt_Unregisterised = 0
453                    | otherwise          = mAX_Real_Float_REG
454 opt_UseDoubleRegs  | opt_Unregisterised = 0
455                    | otherwise          = mAX_Real_Double_REG
456 opt_UseLongRegs    | opt_Unregisterised = 0
457                    | otherwise          = mAX_Real_Long_REG
458 \end{code}
459
460 \begin{code}
461 classifyOpts :: ([CoreToDo],    -- Core-to-Core processing spec
462                  [StgToDo])     -- STG-to-STG   processing spec
463
464 classifyOpts = sep argv [] [] -- accumulators...
465   where
466     sep :: [FAST_STRING]                 -- cmd-line opts (input)
467         -> [CoreToDo] -> [StgToDo]       -- to_do accumulators
468         -> ([CoreToDo], [StgToDo])       -- result
469
470     sep [] core_td stg_td -- all done!
471       = (reverse core_td, reverse stg_td)
472
473 #       define CORE_TD(to_do) sep opts (to_do:core_td) stg_td
474 #       define STG_TD(to_do)  sep opts core_td (to_do:stg_td)
475
476     sep (opt1:opts) core_td stg_td
477       = case (_UNPK_ opt1) of -- the non-"just match a string" options are at the end...
478           ',' : _       -> sep opts core_td stg_td -- it is for the parser
479
480           "-fsimplify"  -> -- gather up SimplifierSwitches specially...
481                            simpl_sep opts defaultSimplSwitches core_td stg_td
482
483           "-ffloat-inwards"  -> CORE_TD(CoreDoFloatInwards)
484           "-ffloat-outwards"      -> CORE_TD(CoreDoFloatOutwards False)
485           "-ffloat-outwards-full" -> CORE_TD(CoreDoFloatOutwards True)
486           "-fliberate-case"  -> CORE_TD(CoreLiberateCase)
487           "-fcse"            -> CORE_TD(CoreCSE)
488           "-fprint-core"     -> CORE_TD(CoreDoPrintCore)
489           "-fstatic-args"    -> CORE_TD(CoreDoStaticArgs)
490           "-fstrictness"     -> CORE_TD(CoreDoStrictness)
491           "-fworker-wrapper" -> CORE_TD(CoreDoWorkerWrapper)
492           "-fspecialise"     -> CORE_TD(CoreDoSpecialising)
493           "-fusagesp"        -> CORE_TD(CoreDoUSPInf)
494           "-fcpr-analyse"    -> CORE_TD(CoreDoCPResult)
495
496           "-fstg-static-args" -> STG_TD(StgDoStaticArgs)
497           "-dstg-stats"       -> STG_TD(D_stg_stats)
498           "-flambda-lift"     -> STG_TD(StgDoLambdaLift)
499           "-fmassage-stg-for-profiling" -> STG_TD(StgDoMassageForProfiling)
500
501           _ -> -- NB: the driver is really supposed to handle bad options
502                sep opts core_td stg_td
503
504     ----------------
505
506     simpl_sep :: [FAST_STRING]            -- cmd-line opts (input)
507               -> [SimplifierSwitch]       -- simplifier-switch accumulator
508               -> [CoreToDo] -> [StgToDo]  -- to_do accumulators
509               -> ([CoreToDo], [StgToDo])  -- result
510
511         -- "simpl_sep" tailcalls "sep" once it's seen one set
512         -- of SimplifierSwitches for a CoreDoSimplify.
513
514 #ifdef DEBUG
515     simpl_sep input@[] simpl_sw core_td stg_td
516       = panic "simpl_sep []"
517 #endif
518
519         -- The SimplifierSwitches should be delimited by "[" and "]".
520
521     simpl_sep (opt1:opts) simpl_sw core_td stg_td
522       = case (_UNPK_ opt1) of
523           "[" -> simpl_sep opts simpl_sw core_td stg_td
524           "]" -> let
525                     this_simpl = CoreDoSimplify (isAmongSimpl simpl_sw)
526                  in
527                  sep opts (this_simpl : core_td) stg_td
528
529           opt -> case matchSimplSw opt of
530                         Just sw -> simpl_sep opts (sw:simpl_sw) core_td stg_td
531                         Nothing -> simpl_sep opts simpl_sw      core_td stg_td
532
533 matchSimplSw opt
534   = firstJust   [ matchSwInt  opt "-fmax-simplifier-iterations"         MaxSimplifierIterations
535                 , matchSwInt  opt "-finline-phase"                      SimplInlinePhase
536                 , matchSwBool opt "-fno-rules"                          DontApplyRules
537                 , matchSwBool opt "-fno-case-of-case"                   NoCaseOfCase
538                 , matchSwBool opt "-flet-to-case"                       SimplLetToCase
539                 ]
540
541 matchSwBool :: String -> String -> a -> Maybe a
542 matchSwBool opt str sw | opt == str = Just sw
543                        | otherwise  = Nothing
544
545 matchSwInt :: String -> String -> (Int -> a) -> Maybe a
546 matchSwInt opt str sw = case startsWith str opt of
547                             Just opt_left -> Just (sw (read opt_left))
548                             Nothing       -> Nothing
549 \end{code}
550
551 %************************************************************************
552 %*                                                                      *
553 \subsection{Switch ordering}
554 %*                                                                      *
555 %************************************************************************
556
557 In spite of the @Produce*@ constructor, these things behave just like
558 enumeration types.
559
560 \begin{code}
561 instance Eq SimplifierSwitch where
562     a == b = tagOf_SimplSwitch a _EQ_ tagOf_SimplSwitch b
563
564 instance Ord SimplifierSwitch where
565     a <  b  = tagOf_SimplSwitch a _LT_ tagOf_SimplSwitch b
566     a <= b  = tagOf_SimplSwitch a _LE_ tagOf_SimplSwitch b
567
568
569 tagOf_SimplSwitch (SimplInlinePhase _)          = ILIT(1)
570 tagOf_SimplSwitch (MaxSimplifierIterations _)   = ILIT(2)
571 tagOf_SimplSwitch DontApplyRules                = ILIT(3)
572 tagOf_SimplSwitch SimplLetToCase                = ILIT(4)
573 tagOf_SimplSwitch NoCaseOfCase                  = ILIT(5)
574
575 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
576
577 lAST_SIMPL_SWITCH_TAG = 5
578 \end{code}
579
580 %************************************************************************
581 %*                                                                      *
582 \subsection{Switch lookup}
583 %*                                                                      *
584 %************************************************************************
585
586 \begin{code}
587 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
588
589 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
590                                         -- in the list; defaults right at the end.
591   = let
592         tidied_on_switches = foldl rm_dups [] on_switches
593                 -- The fold*l* ensures that we keep the latest switches;
594                 -- ie the ones that occur earliest in the list.
595
596         sw_tbl :: Array Int SwitchResult
597         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
598                         all_undefined)
599                  // defined_elems
600
601         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
602
603         defined_elems = map mk_assoc_elem tidied_on_switches
604     in
605     -- (avoid some unboxing, bounds checking, and other horrible things:)
606 #if __GLASGOW_HASKELL__ < 405
607     case sw_tbl of { Array bounds_who_needs_'em stuff ->
608 #else
609     case sw_tbl of { Array _ _ stuff ->
610 #endif
611     \ switch ->
612         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
613 #if __GLASGOW_HASKELL__ < 400
614           Lift v -> v
615 #elif __GLASGOW_HASKELL__ < 403
616           (# _, v #) -> v
617 #else
618           (# v #) -> v
619 #endif
620     }
621   where
622     mk_assoc_elem k@(MaxSimplifierIterations lvl) = (IBOX(tagOf_SimplSwitch k), SwInt lvl)
623     mk_assoc_elem k@(SimplInlinePhase n)          = (IBOX(tagOf_SimplSwitch k), SwInt n)
624     mk_assoc_elem k                               = (IBOX(tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
625
626     -- cannot have duplicates if we are going to use the array thing
627     rm_dups switches_so_far switch
628       = if switch `is_elem` switches_so_far
629         then switches_so_far
630         else switch : switches_so_far
631       where
632         sw `is_elem` []     = False
633         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) _EQ_ (tagOf_SimplSwitch s)
634                             || sw `is_elem` ss
635 \end{code}
636
637 Default settings for simplifier switches
638
639 \begin{code}
640 defaultSimplSwitches = [MaxSimplifierIterations 1]
641 \end{code}
642
643 %************************************************************************
644 %*                                                                      *
645 \subsection{Misc functions for command-line options}
646 %*                                                                      *
647 %************************************************************************
648
649
650 \begin{code}
651 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
652
653 switchIsOn lookup_fn switch
654   = case (lookup_fn switch) of
655       SwBool False -> False
656       _            -> True
657
658 intSwitchSet :: (switch -> SwitchResult)
659              -> (Int -> switch)
660              -> Maybe Int
661
662 intSwitchSet lookup_fn switch
663   = case (lookup_fn (switch (panic "intSwitchSet"))) of
664       SwInt int -> Just int
665       _         -> Nothing
666 \end{code}
667
668 \begin{code}
669 startsWith :: String -> String -> Maybe String
670 -- startsWith pfx (pfx++rest) = Just rest
671
672 startsWith []     str = Just str
673 startsWith (c:cs) (s:ss)
674   = if c /= s then Nothing else startsWith cs ss
675 startsWith  _     []  = Nothing
676
677 endsWith  :: String -> String -> Maybe String
678 endsWith cs ss
679   = case (startsWith (reverse cs) (reverse ss)) of
680       Nothing -> Nothing
681       Just rs -> Just (reverse rs)
682 \end{code}