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