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