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