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