[project @ 1999-12-09 12:30:56 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_source_stats,
47         opt_D_verbose_core2core,
48         opt_D_verbose_stg2stg,
49         opt_DoCoreLinting,
50         opt_DoStgLinting,
51         opt_DoUSPLinting,
52         opt_PprStyle_Debug,
53         opt_PprStyle_NoPrags,
54         opt_PprUserLength,
55
56         -- warning opts
57         opt_WarnDuplicateExports,
58         opt_WarnHiShadows,
59         opt_WarnIncompletePatterns,
60         opt_WarnMissingFields,
61         opt_WarnMissingMethods,
62         opt_WarnMissingSigs,
63         opt_WarnNameShadowing,
64         opt_WarnOverlappingPatterns,
65         opt_WarnSimplePatterns,
66         opt_WarnTypeDefaults,
67         opt_WarnUnusedBinds,
68         opt_WarnUnusedImports,
69         opt_WarnUnusedMatches,
70
71         -- profiling opts
72         opt_AutoSccsOnAllToplevs,
73         opt_AutoSccsOnExportedToplevs,
74         opt_AutoSccsOnIndividualCafs,
75         opt_AutoSccsOnDicts,
76         opt_SccGroup,
77         opt_SccProfilingOn,
78         opt_DoTickyProfiling,
79
80         -- language opts
81         opt_AllStrict,
82         opt_DictsStrict,
83         opt_MaxContextReductionDepth,
84         opt_AllowOverlappingInstances,
85         opt_AllowUndecidableInstances,
86         opt_GlasgowExts,
87         opt_IrrefutableTuples,
88         opt_NumbersStrict,
89         opt_Parallel,
90         opt_SMP,
91
92         -- optimisation opts
93         opt_DoEtaReduction,
94         opt_DoSemiTagging,
95         opt_FoldrBuildOn,
96         opt_LiberateCaseThreshold,
97         opt_StgDoLetNoEscapes,
98         opt_UnfoldCasms,
99         opt_UsageSPOn,
100         opt_UnboxStrictFields,
101         opt_SimplNoPreInlining,
102         opt_SimplDoEtaReduction,
103         opt_SimplDoLambdaEtaExpansion,
104         opt_SimplCaseOfCase,
105         opt_SimplCaseMerge,
106         opt_SimplPedanticBottoms,
107
108         -- Unfolding control
109         opt_UF_HiFileThreshold,
110         opt_UF_CreationThreshold,
111         opt_UF_UseThreshold,
112         opt_UF_ScrutConDiscount,
113         opt_UF_FunAppDiscount,
114         opt_UF_PrimArgDiscount,
115         opt_UF_KeenessFactor,
116         opt_UF_CheapOp,
117         opt_UF_DearOp,
118         opt_UF_NoRepLit,
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.  (The \tr{-G<group>}
174 switch is an exception; it's set to a string, or nothing.)
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   | CoreDoFullLaziness
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   | StgDoUpdateAnalysis
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   | 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_simpl_stats          = opt_D_dump_most || lookUp  SLIT("-ddump-simpl-stats")
334 opt_D_source_stats              = opt_D_dump_most || lookUp  SLIT("-dsource-stats")
335 opt_D_verbose_core2core         = opt_D_dump_all  || lookUp  SLIT("-dverbose-simpl")
336 opt_D_verbose_stg2stg           = opt_D_dump_all  || lookUp  SLIT("-dverbose-stg")
337
338 opt_DoCoreLinting               = lookUp  SLIT("-dcore-lint")
339 opt_DoStgLinting                = lookUp  SLIT("-dstg-lint")
340 opt_DoUSPLinting                = lookUp  SLIT("-dusagesp-lint")
341 opt_PprStyle_NoPrags            = lookUp  SLIT("-dppr-noprags")
342 opt_PprStyle_Debug              = lookUp  SLIT("-dppr-debug")
343 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
344
345 -- warning opts
346 opt_WarnDuplicateExports        = lookUp  SLIT("-fwarn-duplicate-exports")
347 opt_WarnHiShadows               = lookUp  SLIT("-fwarn-hi-shadowing")
348 opt_WarnIncompletePatterns      = lookUp  SLIT("-fwarn-incomplete-patterns")
349 opt_WarnMissingFields           = lookUp  SLIT("-fwarn-missing-fields")
350 opt_WarnMissingMethods          = lookUp  SLIT("-fwarn-missing-methods")
351 opt_WarnMissingSigs             = lookUp  SLIT("-fwarn-missing-signatures")
352 opt_WarnNameShadowing           = lookUp  SLIT("-fwarn-name-shadowing")
353 opt_WarnOverlappingPatterns     = lookUp  SLIT("-fwarn-overlapping-patterns")
354 opt_WarnSimplePatterns          = lookUp  SLIT("-fwarn-simple-patterns")
355 opt_WarnTypeDefaults            = lookUp  SLIT("-fwarn-type-defaults")
356 opt_WarnUnusedBinds             = lookUp  SLIT("-fwarn-unused-binds")
357 opt_WarnUnusedImports           = lookUp  SLIT("-fwarn-unused-imports")
358 opt_WarnUnusedMatches           = lookUp  SLIT("-fwarn-unused-matches")
359
360 -- profiling opts
361 opt_AutoSccsOnAllToplevs        = lookUp  SLIT("-fauto-sccs-on-all-toplevs")
362 opt_AutoSccsOnExportedToplevs   = lookUp  SLIT("-fauto-sccs-on-exported-toplevs")
363 opt_AutoSccsOnIndividualCafs    = lookUp  SLIT("-fauto-sccs-on-individual-cafs")
364 opt_AutoSccsOnDicts             = lookUp  SLIT("-fauto-sccs-on-dicts")
365 opt_SccGroup                    = lookup_str "-G="
366 opt_SccProfilingOn              = lookUp  SLIT("-fscc-profiling")
367 opt_DoTickyProfiling            = lookUp  SLIT("-fticky-ticky")
368
369 -- language opts
370 opt_AllStrict                   = lookUp  SLIT("-fall-strict")
371 opt_DictsStrict                 = lookUp  SLIT("-fdicts-strict")
372 opt_AllowOverlappingInstances   = lookUp  SLIT("-fallow-overlapping-instances")
373 opt_AllowUndecidableInstances   = lookUp  SLIT("-fallow-undecidable-instances")
374 opt_GlasgowExts                 = lookUp  SLIT("-fglasgow-exts")
375 opt_IrrefutableTuples           = lookUp  SLIT("-firrefutable-tuples")
376 opt_MaxContextReductionDepth    = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
377 opt_NumbersStrict               = lookUp  SLIT("-fnumbers-strict")
378 opt_Parallel                    = lookUp  SLIT("-fparallel")
379 opt_SMP                         = lookUp  SLIT("-fsmp")
380
381 -- optimisation opts
382 opt_DoEtaReduction              = lookUp  SLIT("-fdo-eta-reduction")
383 opt_DoSemiTagging               = lookUp  SLIT("-fsemi-tagging")
384 opt_FoldrBuildOn                = lookUp  SLIT("-ffoldr-build-on")
385 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold" (10::Int)
386 opt_StgDoLetNoEscapes           = lookUp  SLIT("-flet-no-escape")
387 opt_UnfoldCasms                 = lookUp SLIT("-funfold-casms-in-hi-file")
388 opt_UsageSPOn                   = lookUp  SLIT("-fusagesp-on")
389 opt_UnboxStrictFields           = lookUp  SLIT("-funbox-strict-fields")
390
391   {-
392    It's a bit unfortunate to have to re-introduce this chap, but on Win32
393    platforms we do need a way of distinguishing between the case when we're
394    compiling a static version of the Prelude and one that's going to be
395    put into a DLL. Why? Because the compiler's wired in modules need to
396    be attributed as either coming from a DLL or not.
397   -}
398 opt_CompilingPrelude            = lookUp  SLIT("-fcompiling-prelude")
399 opt_EmitCExternDecls            = lookUp  SLIT("-femit-extern-decls")
400 opt_EnsureSplittableC           = lookUp  SLIT("-fglobalise-toplev-names")
401 opt_GranMacros                  = lookUp  SLIT("-fgransim")
402 opt_HiMap                       = lookup_str "-himap="       -- file saying where to look for .hi files
403 opt_HiMapSep                    = lookup_def_char "-himap-sep=" ':'
404 opt_HiVersion                   = lookup_def_int "-fhi-version=" 0 -- what version we're compiling.
405 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
406 opt_IgnoreAsserts               = lookUp  SLIT("-fignore-asserts")
407 opt_IgnoreIfacePragmas          = lookUp  SLIT("-fignore-interface-pragmas")
408 opt_NoHiCheck                   = lookUp  SLIT("-fno-hi-version-check")
409 opt_NoImplicitPrelude           = lookUp  SLIT("-fno-implicit-prelude")
410 opt_OmitBlackHoling             = lookUp  SLIT("-dno-black-holing")
411 opt_OmitInterfacePragmas        = lookUp  SLIT("-fomit-interface-pragmas")
412 opt_ProduceC                    = lookup_str "-C="
413 opt_ProduceExportCStubs         = lookup_str "-F="
414 opt_ProduceExportHStubs         = lookup_str "-FH="
415 opt_ProduceHi                   = lookup_str "-hifile=" -- the one to produce this time 
416
417 -- Simplifier switches
418 opt_SimplNoPreInlining          = lookUp SLIT("-fno-pre-inlining")
419         -- NoPreInlining is there just to see how bad things
420         -- get if you don't do it!
421 opt_SimplDoEtaReduction         = lookUp SLIT("-fdo-eta-reduction")
422 opt_SimplDoLambdaEtaExpansion   = lookUp SLIT("-fdo-lambda-eta-expansion")
423 opt_SimplCaseOfCase             = lookUp SLIT("-fcase-of-case")
424 opt_SimplCaseMerge              = lookUp SLIT("-fcase-merge")
425 opt_SimplPedanticBottoms        = lookUp SLIT("-fpedantic-bottoms")
426
427 -- Unfolding control
428 opt_UF_HiFileThreshold          = lookup_def_int "-funfolding-interface-threshold" (30::Int)
429 opt_UF_CreationThreshold        = lookup_def_int "-funfolding-creation-threshold"  (30::Int)
430 opt_UF_UseThreshold             = lookup_def_int "-funfolding-use-threshold"       (8::Int)     -- Discounts can be big
431 opt_UF_ScrutConDiscount         = lookup_def_int "-funfolding-con-discount"        (2::Int)
432 opt_UF_FunAppDiscount           = lookup_def_int "-funfolding-fun-discount"        (6::Int)     -- It's great to inline a fn
433 opt_UF_PrimArgDiscount          = lookup_def_int "-funfolding-prim-discount"       (1::Int)
434 opt_UF_KeenessFactor            = lookup_def_float "-funfolding-keeness-factor"    (2.0::Float)
435
436 opt_UF_CheapOp  = ( 0 :: Int)   -- Only one instruction; and the args are charged for
437 opt_UF_DearOp   = ( 4 :: Int)
438 opt_UF_NoRepLit = ( 20 :: Int)  -- Strings can be pretty big
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           "-ffull-laziness"  -> CORE_TD(CoreDoFullLaziness)
483           "-fliberate-case"  -> CORE_TD(CoreLiberateCase)
484           "-fcse"            -> CORE_TD(CoreCSE)
485           "-fprint-core"     -> CORE_TD(CoreDoPrintCore)
486           "-fstatic-args"    -> CORE_TD(CoreDoStaticArgs)
487           "-fstrictness"     -> CORE_TD(CoreDoStrictness)
488           "-fworker-wrapper" -> CORE_TD(CoreDoWorkerWrapper)
489           "-fspecialise"     -> CORE_TD(CoreDoSpecialising)
490           "-fusagesp"        -> CORE_TD(CoreDoUSPInf)
491           "-fcpr-analyse"    -> CORE_TD(CoreDoCPResult)
492
493           "-fstg-static-args" -> STG_TD(StgDoStaticArgs)
494           "-fupdate-analysis" -> STG_TD(StgDoUpdateAnalysis)
495           "-dstg-stats"       -> STG_TD(D_stg_stats)
496           "-flambda-lift"     -> STG_TD(StgDoLambdaLift)
497           "-fmassage-stg-for-profiling" -> STG_TD(StgDoMassageForProfiling)
498
499           _ -> -- NB: the driver is really supposed to handle bad options
500                sep opts core_td stg_td
501
502     ----------------
503
504     simpl_sep :: [FAST_STRING]            -- cmd-line opts (input)
505               -> [SimplifierSwitch]       -- simplifier-switch accumulator
506               -> [CoreToDo] -> [StgToDo]  -- to_do accumulators
507               -> ([CoreToDo], [StgToDo])  -- result
508
509         -- "simpl_sep" tailcalls "sep" once it's seen one set
510         -- of SimplifierSwitches for a CoreDoSimplify.
511
512 #ifdef DEBUG
513     simpl_sep input@[] simpl_sw core_td stg_td
514       = panic "simpl_sep []"
515 #endif
516
517         -- The SimplifierSwitches should be delimited by "[" and "]".
518
519     simpl_sep (opt1:opts) simpl_sw core_td stg_td
520       = case (_UNPK_ opt1) of
521           "[" -> simpl_sep opts simpl_sw core_td stg_td
522           "]" -> let
523                     this_simpl = CoreDoSimplify (isAmongSimpl simpl_sw)
524                  in
525                  sep opts (this_simpl : core_td) stg_td
526
527           opt -> case matchSimplSw opt of
528                         Just sw -> simpl_sep opts (sw:simpl_sw) core_td stg_td
529                         Nothing -> simpl_sep opts simpl_sw      core_td stg_td
530
531 matchSimplSw opt
532   = firstJust   [ matchSwInt  opt "-fmax-simplifier-iterations"         MaxSimplifierIterations
533                 , matchSwInt  opt "-finline-phase"                      SimplInlinePhase
534                 , matchSwBool opt "-fno-rules"                          DontApplyRules
535                 , matchSwBool opt "-flet-to-case"                       SimplLetToCase
536                 ]
537
538 matchSwBool :: String -> String -> a -> Maybe a
539 matchSwBool opt str sw | opt == str = Just sw
540                        | otherwise  = Nothing
541
542 matchSwInt :: String -> String -> (Int -> a) -> Maybe a
543 matchSwInt opt str sw = case startsWith str opt of
544                             Just opt_left -> Just (sw (read opt_left))
545                             Nothing       -> Nothing
546 \end{code}
547
548 %************************************************************************
549 %*                                                                      *
550 \subsection{Switch ordering}
551 %*                                                                      *
552 %************************************************************************
553
554 In spite of the @Produce*@ and @SccGroup@ constructors, these things
555 behave just like enumeration types.
556
557 \begin{code}
558 instance Eq SimplifierSwitch where
559     a == b = tagOf_SimplSwitch a _EQ_ tagOf_SimplSwitch b
560
561 instance Ord SimplifierSwitch where
562     a <  b  = tagOf_SimplSwitch a _LT_ tagOf_SimplSwitch b
563     a <= b  = tagOf_SimplSwitch a _LE_ tagOf_SimplSwitch b
564
565
566 tagOf_SimplSwitch (SimplInlinePhase _)          = ILIT(1)
567 tagOf_SimplSwitch (MaxSimplifierIterations _)   = ILIT(2)
568 tagOf_SimplSwitch DontApplyRules                = ILIT(3)
569 tagOf_SimplSwitch SimplLetToCase                = ILIT(4)
570
571 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
572
573 lAST_SIMPL_SWITCH_TAG = 4
574 \end{code}
575
576 %************************************************************************
577 %*                                                                      *
578 \subsection{Switch lookup}
579 %*                                                                      *
580 %************************************************************************
581
582 \begin{code}
583 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
584
585 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
586                                         -- in the list; defaults right at the end.
587   = let
588         tidied_on_switches = foldl rm_dups [] on_switches
589                 -- The fold*l* ensures that we keep the latest switches;
590                 -- ie the ones that occur earliest in the list.
591
592         sw_tbl :: Array Int SwitchResult
593         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
594                         all_undefined)
595                  // defined_elems
596
597         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
598
599         defined_elems = map mk_assoc_elem tidied_on_switches
600     in
601     -- (avoid some unboxing, bounds checking, and other horrible things:)
602 #if __GLASGOW_HASKELL__ < 405
603     case sw_tbl of { Array bounds_who_needs_'em stuff ->
604 #else
605     case sw_tbl of { Array _ _ stuff ->
606 #endif
607     \ switch ->
608         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
609 #if __GLASGOW_HASKELL__ < 400
610           Lift v -> v
611 #elif __GLASGOW_HASKELL__ < 403
612           (# _, v #) -> v
613 #else
614           (# v #) -> v
615 #endif
616     }
617   where
618     mk_assoc_elem k@(MaxSimplifierIterations lvl) = (IBOX(tagOf_SimplSwitch k), SwInt lvl)
619     mk_assoc_elem k@(SimplInlinePhase n)          = (IBOX(tagOf_SimplSwitch k), SwInt n)
620     mk_assoc_elem k                               = (IBOX(tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
621
622     -- cannot have duplicates if we are going to use the array thing
623     rm_dups switches_so_far switch
624       = if switch `is_elem` switches_so_far
625         then switches_so_far
626         else switch : switches_so_far
627       where
628         sw `is_elem` []     = False
629         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) _EQ_ (tagOf_SimplSwitch s)
630                             || sw `is_elem` ss
631 \end{code}
632
633 Default settings for simplifier switches
634
635 \begin{code}
636 defaultSimplSwitches = [MaxSimplifierIterations 1]
637 \end{code}
638
639 %************************************************************************
640 %*                                                                      *
641 \subsection{Misc functions for command-line options}
642 %*                                                                      *
643 %************************************************************************
644
645
646 \begin{code}
647 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
648
649 switchIsOn lookup_fn switch
650   = case (lookup_fn switch) of
651       SwBool False -> False
652       _            -> True
653
654 intSwitchSet :: (switch -> SwitchResult)
655              -> (Int -> switch)
656              -> Maybe Int
657
658 intSwitchSet lookup_fn switch
659   = case (lookup_fn (switch (panic "intSwitchSet"))) of
660       SwInt int -> Just int
661       _         -> Nothing
662 \end{code}
663
664 \begin{code}
665 startsWith :: String -> String -> Maybe String
666 -- startsWith pfx (pfx++rest) = Just rest
667
668 startsWith []     str = Just str
669 startsWith (c:cs) (s:ss)
670   = if c /= s then Nothing else startsWith cs ss
671 startsWith  _     []  = Nothing
672
673 endsWith  :: String -> String -> Maybe String
674 endsWith cs ss
675   = case (startsWith (reverse cs) (reverse ss)) of
676       Nothing -> Nothing
677       Just rs -> Just (reverse rs)
678 \end{code}