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