89c6fc8299e9c2d40e5f57da7cb6aeca1857817c
[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         opt_AllStrict,
18         opt_AllowOverlappingInstances,
19         opt_AllowUndecidableInstances,
20         opt_AutoSccsOnAllToplevs,
21         opt_AutoSccsOnExportedToplevs,
22         opt_AutoSccsOnIndividualCafs,
23         opt_CompilingPrelude,
24         opt_D_dump_absC,
25         opt_D_dump_asm,
26         opt_D_dump_deriv,
27         opt_D_dump_ds,
28         opt_D_dump_flatC,
29         opt_D_dump_inlinings,
30         opt_D_dump_foreign,
31         opt_D_dump_occur_anal,
32         opt_D_dump_rdr,
33         opt_D_dump_realC,
34         opt_D_dump_rn,
35         opt_D_dump_simpl,
36         opt_D_dump_simpl_iterations,
37         opt_D_dump_spec,
38         opt_D_dump_stg,
39         opt_D_dump_stranal,
40         opt_D_dump_tc,
41         opt_D_show_passes,
42         opt_D_show_rn_trace,
43         opt_D_show_rn_imports,
44         opt_D_simplifier_stats,
45         opt_D_source_stats,
46         opt_D_verbose_core2core,
47         opt_D_verbose_stg2stg,
48         opt_DictsStrict,
49         opt_DoCoreLinting,
50         opt_DoStgLinting,
51         opt_DoSemiTagging,
52         opt_DoEtaReduction,
53         opt_DoTickyProfiling,
54         opt_EmitCExternDecls,
55         opt_EnsureSplittableC,
56         opt_FoldrBuildOn,
57         opt_GlasgowExts,
58         opt_GranMacros,
59         opt_HiMap,
60         opt_HiVersion,
61         opt_IgnoreIfacePragmas,
62         opt_IrrefutableTuples,
63         opt_LiberateCaseThreshold,
64         opt_MaxContextReductionDepth,
65         opt_MultiParamClasses,
66         opt_NoHiCheck,
67         opt_NoImplicitPrelude,
68         opt_NoPreInlining,
69         opt_NumbersStrict,
70         opt_OmitBlackHoling,
71         opt_OmitInterfacePragmas,
72         opt_PprStyle_NoPrags,
73         opt_PprStyle_Debug,
74         opt_PprUserLength,
75         opt_ProduceC,
76         opt_ProduceHi,
77         opt_ProduceS,
78         opt_ProduceExportCStubs,
79         opt_ProduceExportHStubs,
80         opt_ReportCompile,
81         opt_SccGroup,
82         opt_SccProfilingOn,
83         opt_SourceUnchanged,
84         opt_Static,
85         opt_StgDoLetNoEscapes,
86         opt_Parallel,
87
88         opt_InterfaceUnfoldThreshold,
89         opt_UnfoldCasms,
90         opt_UnfoldingCreationThreshold,
91         opt_UnfoldingConDiscount,
92         opt_UnfoldingUseThreshold,
93         opt_UnfoldingKeenessFactor,
94
95         opt_Verbose,
96
97         opt_WarnNameShadowing,
98         opt_WarnUnusedMatches,
99         opt_WarnUnusedBinds,
100         opt_WarnUnusedImports,
101         opt_WarnIncompletePatterns,
102         opt_WarnOverlappingPatterns,
103         opt_WarnSimplePatterns,
104         opt_WarnTypeDefaults,
105         opt_WarnMissingMethods,
106         opt_WarnDuplicateExports,
107         opt_WarnHiShadows,
108         opt_WarnMissingSigs,
109         opt_PruneTyDecls, opt_PruneInstDecls,
110         opt_D_show_rn_stats
111     ) where
112
113 #include "HsVersions.h"
114
115 import Array    ( array, (//) )
116 import GlaExts
117 import Argv
118 import Constants        -- Default values for some flags
119
120 import Maybes           ( assocMaybe, firstJust, maybeToBool )
121 import Panic            ( panic, panic# )
122
123 #if __GLASGOW_HASKELL__ < 301
124 import ArrBase  ( Array(..) )
125 #else
126 import PrelArr  ( Array(..) )
127 #endif
128 \end{code}
129
130 A command-line {\em switch} is (generally) either on or off; e.g., the
131 ``verbose'' (-v) switch is either on or off.  (The \tr{-G<group>}
132 switch is an exception; it's set to a string, or nothing.)
133
134 A list of {\em ToDo}s is things to be done in a particular part of
135 processing.  A (fictitious) example for the Core-to-Core simplifier
136 might be: run the simplifier, then run the strictness analyser, then
137 run the simplifier again (three ``todos'').
138
139 There are three ``to-do processing centers'' at the moment.  In the
140 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
141 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
142 (\tr{simplStg/SimplStg.lhs}).
143
144 %************************************************************************
145 %*                                                                      *
146 \subsection{Datatypes associated with command-line options}
147 %*                                                                      *
148 %************************************************************************
149
150 \begin{code}
151 data SwitchResult
152   = SwBool      Bool            -- on/off
153   | SwString    FAST_STRING     -- nothing or a String
154   | SwInt       Int             -- nothing or an Int
155 \end{code}
156
157 \begin{code}
158 data CoreToDo           -- These are diff core-to-core passes,
159                         -- which may be invoked in any order,
160                         -- as many times as you like.
161
162   = CoreDoSimplify      -- The core-to-core simplifier.
163         (SimplifierSwitch -> SwitchResult)
164                         -- Each run of the simplifier can take a different
165                         -- set of simplifier-specific flags.
166   | CoreDoCalcInlinings1
167   | CoreDoCalcInlinings2
168   | CoreDoFloatInwards
169   | CoreDoFullLaziness
170   | CoreLiberateCase
171   | CoreDoPrintCore
172   | CoreDoStaticArgs
173   | CoreDoStrictness
174   | CoreDoSpecialising
175   | CoreDoFoldrBuildWorkerWrapper
176   | CoreDoFoldrBuildWWAnal
177 \end{code}
178
179 \begin{code}
180 data StgToDo
181   = StgDoStaticArgs
182   | StgDoUpdateAnalysis
183   | StgDoLambdaLift
184   | StgDoMassageForProfiling  -- should be (next to) last
185   -- There's also setStgVarInfo, but its absolute "lastness"
186   -- is so critical that it is hardwired in (no flag).
187   | D_stg_stats
188 \end{code}
189
190 \begin{code}
191 data SimplifierSwitch
192   = SimplOkToDupCode
193   | SimplFloatLetsExposingWHNF
194   | SimplOkToFloatPrimOps
195   | SimplAlwaysFloatLetsFromLets
196   | SimplDoCaseElim
197   | SimplCaseOfCase
198   | SimplLetToCase
199   | SimplMayDeleteConjurableIds
200   | SimplPedanticBottoms -- see Simplifier for an explanation
201   | SimplDoArityExpand   -- expand arity of bindings
202   | SimplDoFoldrBuild    -- This is the per-simplification flag;
203                          -- see also FoldrBuildOn, used elsewhere
204                          -- in the compiler.
205   | SimplDoInlineFoldrBuild
206                          -- inline foldr/build (*after* f/b rule is used)
207
208   | IgnoreINLINEPragma
209   | SimplDoLambdaEtaExpansion
210
211   | EssentialUnfoldingsOnly -- never mind the thresholds, only
212                             -- do unfoldings that *must* be done
213                             -- (to saturate constructors and primitives)
214
215   | MaxSimplifierIterations Int
216
217   | SimplNoLetFromCase      -- used when turning off floating entirely
218   | SimplNoLetFromApp       -- (for experimentation only) WDP 95/10
219   | SimplNoLetFromStrictLet
220
221   | SimplCaseMerge
222   | SimplPleaseClone
223 \end{code}
224
225 %************************************************************************
226 %*                                                                      *
227 \subsection{Classifying command-line options}
228 %*                                                                      *
229 %************************************************************************
230
231 \begin{code}
232 lookUp           :: FAST_STRING -> Bool
233 lookup_int       :: String -> Maybe Int
234 lookup_def_int   :: String -> Int -> Int
235 lookup_def_float :: String -> Float -> Float
236 lookup_str       :: String -> Maybe String
237
238 lookUp     sw = maybeToBool (assoc_opts sw)
239         
240 lookup_str sw = firstJust (map (startsWith sw) unpacked_opts)
241
242 lookup_int sw = case (lookup_str sw) of
243                   Nothing -> Nothing
244                   Just xx -> Just (read xx)
245
246 lookup_def_int sw def = case (lookup_str sw) of
247                             Nothing -> def              -- Use default
248                             Just xx -> read xx
249
250 lookup_def_float sw def = case (lookup_str sw) of
251                             Nothing -> def              -- Use default
252                             Just xx -> read xx
253
254 assoc_opts    = assocMaybe [ (a, True) | a <- argv ]
255 unpacked_opts = map _UNPK_ argv
256
257 {-
258  Putting the compiler options into temporary at-files
259  may turn out to be necessary later on if we turn hsc into
260  a pure Win32 application where I think there's a command-line
261  length limit of 255. unpacked_opts understands the @ option.
262
263 assoc_opts    = assocMaybe [ (_PK_ a, True) | a <- unpacked_opts ]
264
265 unpacked_opts :: [String]
266 unpacked_opts =
267   concat $
268   map (expandAts) $
269   map _UNPK_ argv
270   where
271    expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
272    expandAts l = [l]
273 -}
274 \end{code}
275
276 \begin{code}
277 opt_AllStrict                   = lookUp  SLIT("-fall-strict")
278 opt_AllowOverlappingInstances   = lookUp  SLIT("-fallow-overlapping-instances")
279 opt_AllowUndecidableInstances   = lookUp  SLIT("-fallow-undecidable-instances")
280 opt_AutoSccsOnAllToplevs        = lookUp  SLIT("-fauto-sccs-on-all-toplevs")
281 opt_AutoSccsOnExportedToplevs   = lookUp  SLIT("-fauto-sccs-on-exported-toplevs")
282 opt_AutoSccsOnIndividualCafs    = lookUp  SLIT("-fauto-sccs-on-individual-cafs")
283   {-
284    It's a bit unfortunate to have to re-introduce this chap, but on Win32
285    platforms we do need a way of distinguishing between the case when we're
286    compiling a static version of the Prelude and one that's going to be
287    put into a DLL. Why? Because the compiler's wired in modules need to
288    be attributed as either coming from a DLL or not.
289   -}
290 opt_CompilingPrelude            = lookUp  SLIT("-fcompiling-prelude")
291 opt_D_dump_absC                 = lookUp  SLIT("-ddump-absC")
292 opt_D_dump_asm                  = lookUp  SLIT("-ddump-asm")
293 opt_D_dump_deriv                = lookUp  SLIT("-ddump-deriv")
294 opt_D_dump_ds                   = lookUp  SLIT("-ddump-ds")
295 opt_D_dump_flatC                = lookUp  SLIT("-ddump-flatC")
296 opt_D_dump_inlinings            = lookUp  SLIT("-ddump-inlinings")
297 opt_D_dump_foreign              = lookUp  SLIT("-ddump-foreign-stubs")
298 opt_D_dump_occur_anal           = lookUp  SLIT("-ddump-occur-anal")
299 opt_D_dump_rdr                  = lookUp  SLIT("-ddump-rdr")
300 opt_D_dump_realC                = lookUp  SLIT("-ddump-realC")
301 opt_D_dump_rn                   = lookUp  SLIT("-ddump-rn")
302 opt_D_dump_simpl                = lookUp  SLIT("-ddump-simpl")
303 opt_D_dump_simpl_iterations     = lookUp  SLIT("-ddump-simpl-iterations")
304 opt_D_dump_spec                 = lookUp  SLIT("-ddump-spec")
305 opt_D_dump_stg                  = lookUp  SLIT("-ddump-stg")
306 opt_D_dump_stranal              = lookUp  SLIT("-ddump-stranal")
307 opt_D_dump_tc                   = lookUp  SLIT("-ddump-tc")
308 opt_D_show_passes               = lookUp  SLIT("-dshow-passes")
309 opt_D_show_rn_trace             = lookUp  SLIT("-dshow-rn-trace")
310 opt_D_show_rn_imports           = lookUp  SLIT("-dshow-rn-imports")
311 opt_D_simplifier_stats          = lookUp  SLIT("-dsimplifier-stats")
312 opt_D_source_stats              = lookUp  SLIT("-dsource-stats")
313 opt_D_verbose_core2core         = lookUp  SLIT("-dverbose-simpl")
314 opt_D_verbose_stg2stg           = lookUp  SLIT("-dverbose-stg")
315 opt_DictsStrict                 = lookUp  SLIT("-fdicts-strict")
316 opt_DoCoreLinting               = lookUp  SLIT("-dcore-lint")
317 opt_DoStgLinting                = lookUp  SLIT("-dstg-lint")
318 opt_DoEtaReduction              = lookUp  SLIT("-fdo-eta-reduction")
319 opt_DoSemiTagging               = lookUp  SLIT("-fsemi-tagging")
320 opt_DoTickyProfiling            = lookUp  SLIT("-fticky-ticky")
321 opt_EmitCExternDecls            = lookUp  SLIT("-femit-extern-decls")
322 opt_EnsureSplittableC           = lookUp  SLIT("-fglobalise-toplev-names")
323 opt_FoldrBuildOn                = lookUp  SLIT("-ffoldr-build-on")
324 opt_GranMacros                  = lookUp  SLIT("-fgransim")
325 opt_GlasgowExts                 = lookUp  SLIT("-fglasgow-exts")
326 opt_HiMap                       = lookup_str "-himap="       -- file saying where to look for .hi files
327 opt_HiVersion                   = lookup_def_int "-fhi-version=" 0 -- what version we're compiling.
328 opt_IgnoreIfacePragmas          = lookUp  SLIT("-fignore-interface-pragmas")
329 opt_IrrefutableTuples           = lookUp  SLIT("-firrefutable-tuples")
330 opt_MaxContextReductionDepth    = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
331 opt_MultiParamClasses           = opt_GlasgowExts
332 opt_NoHiCheck                   = lookUp  SLIT("-fno-hi-version-check")
333 opt_NoImplicitPrelude           = lookUp  SLIT("-fno-implicit-prelude")
334 opt_NoPreInlining               = lookUp  SLIT("-fno-pre-inlining")
335 opt_NumbersStrict               = lookUp  SLIT("-fnumbers-strict")
336 opt_OmitBlackHoling             = lookUp  SLIT("-dno-black-holing")
337 opt_OmitInterfacePragmas        = lookUp  SLIT("-fomit-interface-pragmas")
338 opt_PprStyle_NoPrags            = lookUp  SLIT("-dppr-noprags")
339 opt_PprStyle_Debug              = lookUp  SLIT("-dppr-debug")
340 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
341 opt_ProduceC                    = lookup_str "-C="
342 opt_ProduceS                    = lookup_str "-S="
343 opt_ProduceExportCStubs         = lookup_str "-F="
344 opt_ProduceExportHStubs         = lookup_str "-FH="
345 opt_ProduceHi                   = lookup_str "-hifile=" -- the one to produce this time 
346 opt_ReportCompile                = lookUp SLIT("-freport-compile")
347 opt_SccProfilingOn              = lookUp  SLIT("-fscc-profiling")
348 opt_SourceUnchanged             = lookUp  SLIT("-fsource-unchanged")
349 opt_StgDoLetNoEscapes           = lookUp  SLIT("-flet-no-escape")
350 opt_Parallel                    = lookUp  SLIT("-fparallel")
351 opt_Static                      = lookUp  SLIT("-static")
352 opt_SccGroup                    = lookup_str "-G="
353 opt_Verbose                     = lookUp  SLIT("-v")
354
355 opt_UnfoldCasms                 = lookUp SLIT("-funfold-casms-in-hi-file")
356 opt_InterfaceUnfoldThreshold    = lookup_def_int "-funfolding-interface-threshold" iNTERFACE_UNFOLD_THRESHOLD
357 opt_UnfoldingCreationThreshold  = lookup_def_int "-funfolding-creation-threshold"  uNFOLDING_CREATION_THRESHOLD
358 opt_UnfoldingUseThreshold       = lookup_def_int "-funfolding-use-threshold"       uNFOLDING_USE_THRESHOLD
359 opt_UnfoldingConDiscount        = lookup_def_int "-funfolding-con-discount"        uNFOLDING_CON_DISCOUNT_WEIGHT
360                         
361 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold"       lIBERATE_CASE_THRESHOLD
362 opt_UnfoldingKeenessFactor      = lookup_def_float "-funfolding-keeness-factor"    uNFOLDING_KEENESS_FACTOR
363 opt_WarnNameShadowing           = lookUp  SLIT("-fwarn-name-shadowing")
364 opt_WarnHiShadows               = lookUp  SLIT("-fwarn-hi-shadowing")
365 opt_WarnIncompletePatterns      = lookUp  SLIT("-fwarn-incomplete-patterns")
366 opt_WarnOverlappingPatterns     = lookUp  SLIT("-fwarn-overlapping-patterns")
367 opt_WarnSimplePatterns          = lookUp  SLIT("-fwarn-simple-patterns")
368 opt_WarnTypeDefaults            = lookUp  SLIT("-fwarn-type-defaults")
369 opt_WarnUnusedMatches           = lookUp  SLIT("-fwarn-unused-matches")
370 opt_WarnUnusedBinds             = lookUp  SLIT("-fwarn-unused-binds")
371 opt_WarnUnusedImports           = lookUp  SLIT("-fwarn-unused-imports")
372 opt_WarnMissingMethods          = lookUp  SLIT("-fwarn-missing-methods")
373 opt_WarnDuplicateExports        = lookUp  SLIT("-fwarn-duplicate-exports")
374 opt_WarnMissingSigs             = lookUp  SLIT("-fwarn-missing-signatures")
375 opt_PruneTyDecls                = not (lookUp SLIT("-fno-prune-tydecls"))
376 opt_PruneInstDecls              = not (lookUp SLIT("-fno-prune-instdecls"))
377 opt_D_show_rn_stats             = lookUp SLIT("-dshow-rn-stats")
378
379 -- opt_UnfoldingOverrideThreshold       = lookup_int "-funfolding-override-threshold"
380 \end{code}
381
382 \begin{code}
383 classifyOpts :: ([CoreToDo],    -- Core-to-Core processing spec
384                  [StgToDo])     -- STG-to-STG   processing spec
385
386 classifyOpts = sep argv [] [] -- accumulators...
387   where
388     sep :: [FAST_STRING]                 -- cmd-line opts (input)
389         -> [CoreToDo] -> [StgToDo]       -- to_do accumulators
390         -> ([CoreToDo], [StgToDo])       -- result
391
392     sep [] core_td stg_td -- all done!
393       = (reverse core_td, reverse stg_td)
394
395 #       define CORE_TD(to_do) sep opts (to_do:core_td) stg_td
396 #       define STG_TD(to_do)  sep opts core_td (to_do:stg_td)
397
398     sep (opt1:opts) core_td stg_td
399       = case (_UNPK_ opt1) of -- the non-"just match a string" options are at the end...
400           ',' : _       -> sep opts core_td stg_td -- it is for the parser
401
402           "-fsimplify"  -> -- gather up SimplifierSwitches specially...
403                            simpl_sep opts defaultSimplSwitches core_td stg_td
404
405           "-fcalc-inlinings1"-> CORE_TD(CoreDoCalcInlinings1)
406           "-fcalc-inlinings2"-> CORE_TD(CoreDoCalcInlinings2)
407           "-ffloat-inwards"  -> CORE_TD(CoreDoFloatInwards)
408           "-ffull-laziness"  -> CORE_TD(CoreDoFullLaziness)
409           "-fliberate-case"  -> CORE_TD(CoreLiberateCase)
410           "-fprint-core"     -> CORE_TD(CoreDoPrintCore)
411           "-fstatic-args"    -> CORE_TD(CoreDoStaticArgs)
412           "-fstrictness"     -> CORE_TD(CoreDoStrictness)
413           "-fspecialise"     -> CORE_TD(CoreDoSpecialising)
414           "-ffoldr-build-worker-wrapper"  -> CORE_TD(CoreDoFoldrBuildWorkerWrapper)
415           "-ffoldr-build-ww-anal"  -> CORE_TD(CoreDoFoldrBuildWWAnal)
416
417           "-fstg-static-args" -> STG_TD(StgDoStaticArgs)
418           "-fupdate-analysis" -> STG_TD(StgDoUpdateAnalysis)
419           "-dstg-stats"       -> STG_TD(D_stg_stats)
420           "-flambda-lift"     -> STG_TD(StgDoLambdaLift)
421           "-fmassage-stg-for-profiling" -> STG_TD(StgDoMassageForProfiling)
422
423           _ -> -- NB: the driver is really supposed to handle bad options
424                sep opts core_td stg_td
425
426     ----------------
427
428     simpl_sep :: [FAST_STRING]            -- cmd-line opts (input)
429               -> [SimplifierSwitch]       -- simplifier-switch accumulator
430               -> [CoreToDo] -> [StgToDo]  -- to_do accumulators
431               -> ([CoreToDo], [StgToDo])  -- result
432
433         -- "simpl_sep" tailcalls "sep" once it's seen one set
434         -- of SimplifierSwitches for a CoreDoSimplify.
435
436 #ifdef DEBUG
437     simpl_sep input@[] simpl_sw core_td stg_td
438       = panic "simpl_sep []"
439 #endif
440
441         -- The SimplifierSwitches should be delimited by "[" and "]".
442
443     simpl_sep (opt1:opts) simpl_sw core_td stg_td
444       = case (_UNPK_ opt1) of
445           "[" -> simpl_sep opts simpl_sw core_td stg_td
446           "]" -> let
447                     this_simpl = CoreDoSimplify (isAmongSimpl simpl_sw)
448                  in
449                  sep opts (this_simpl : core_td) stg_td
450
451 #         define SIMPL_SW(sw) simpl_sep opts (sw:simpl_sw) core_td stg_td
452
453           -- the non-"just match a string" options are at the end...
454           "-fcode-duplication-ok"           -> SIMPL_SW(SimplOkToDupCode)
455           "-ffloat-lets-exposing-whnf"      -> SIMPL_SW(SimplFloatLetsExposingWHNF)
456           "-ffloat-primops-ok"              -> SIMPL_SW(SimplOkToFloatPrimOps)
457           "-falways-float-lets-from-lets"   -> SIMPL_SW(SimplAlwaysFloatLetsFromLets)
458           "-fdo-case-elim"                  -> SIMPL_SW(SimplDoCaseElim)
459           "-fdo-lambda-eta-expansion"       -> SIMPL_SW(SimplDoLambdaEtaExpansion)
460           "-fdo-foldr-build"                -> SIMPL_SW(SimplDoFoldrBuild)
461           "-fdo-arity-expand"               -> SIMPL_SW(SimplDoArityExpand)
462           "-fdo-inline-foldr-build"         -> SIMPL_SW(SimplDoInlineFoldrBuild)
463           "-fcase-of-case"                  -> SIMPL_SW(SimplCaseOfCase)
464           "-fcase-merge"                    -> SIMPL_SW(SimplCaseMerge)
465           "-flet-to-case"                   -> SIMPL_SW(SimplLetToCase)
466           "-fpedantic-bottoms"              -> SIMPL_SW(SimplPedanticBottoms)
467           "-fmay-delete-conjurable-ids"     -> SIMPL_SW(SimplMayDeleteConjurableIds)
468           "-fessential-unfoldings-only"     -> SIMPL_SW(EssentialUnfoldingsOnly)
469           "-fignore-inline-pragma"          -> SIMPL_SW(IgnoreINLINEPragma)
470           "-fno-let-from-case"              -> SIMPL_SW(SimplNoLetFromCase)
471           "-fno-let-from-app"               -> SIMPL_SW(SimplNoLetFromApp)
472           "-fno-let-from-strict-let"        -> SIMPL_SW(SimplNoLetFromStrictLet)
473           "-fclone-binds"                   -> SIMPL_SW(SimplPleaseClone)
474
475           o | starts_with_msi  -> SIMPL_SW(MaxSimplifierIterations (read after_msi))
476            where
477             maybe_msi           = startsWith "-fmax-simplifier-iterations"   o
478             starts_with_msi     = maybeToBool maybe_msi
479             (Just after_msi)    = maybe_msi
480
481           _ -> -- NB: the driver is really supposed to handle bad options
482                simpl_sep opts simpl_sw core_td stg_td
483 \end{code}
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{Switch ordering}
488 %*                                                                      *
489 %************************************************************************
490
491 In spite of the @Produce*@ and @SccGroup@ constructors, these things
492 behave just like enumeration types.
493
494 \begin{code}
495 instance Eq SimplifierSwitch where
496     a == b = tagOf_SimplSwitch a _EQ_ tagOf_SimplSwitch b
497
498 instance Ord SimplifierSwitch where
499     a <  b  = tagOf_SimplSwitch a _LT_ tagOf_SimplSwitch b
500     a <= b  = tagOf_SimplSwitch a _LE_ tagOf_SimplSwitch b
501
502 tagOf_SimplSwitch SimplOkToDupCode              =(ILIT(0) :: FAST_INT)
503 tagOf_SimplSwitch SimplFloatLetsExposingWHNF    = ILIT(1)
504 tagOf_SimplSwitch SimplOkToFloatPrimOps         = ILIT(2)
505 tagOf_SimplSwitch SimplAlwaysFloatLetsFromLets  = ILIT(3)
506 tagOf_SimplSwitch SimplDoCaseElim               = ILIT(4)
507 tagOf_SimplSwitch SimplCaseOfCase               = ILIT(6)
508 tagOf_SimplSwitch SimplLetToCase                = ILIT(7)
509 tagOf_SimplSwitch SimplMayDeleteConjurableIds   = ILIT(9)
510 tagOf_SimplSwitch SimplPedanticBottoms          = ILIT(10)
511 tagOf_SimplSwitch SimplDoArityExpand            = ILIT(11)
512 tagOf_SimplSwitch SimplDoFoldrBuild             = ILIT(12)
513 tagOf_SimplSwitch SimplDoInlineFoldrBuild       = ILIT(14)
514 tagOf_SimplSwitch IgnoreINLINEPragma            = ILIT(15)
515 tagOf_SimplSwitch SimplDoLambdaEtaExpansion     = ILIT(16)
516 tagOf_SimplSwitch EssentialUnfoldingsOnly       = ILIT(19)
517 tagOf_SimplSwitch (MaxSimplifierIterations _)   = ILIT(21)
518 tagOf_SimplSwitch SimplNoLetFromCase            = ILIT(27)
519 tagOf_SimplSwitch SimplNoLetFromApp             = ILIT(28)
520 tagOf_SimplSwitch SimplNoLetFromStrictLet       = ILIT(29)
521 tagOf_SimplSwitch SimplCaseMerge                = ILIT(31)
522 tagOf_SimplSwitch SimplPleaseClone              = ILIT(32)
523
524 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
525
526 tagOf_SimplSwitch _ = panic# "tagOf_SimplSwitch"
527
528 lAST_SIMPL_SWITCH_TAG = IBOX(tagOf_SimplSwitch SimplPleaseClone)
529 \end{code}
530
531 %************************************************************************
532 %*                                                                      *
533 \subsection{Switch lookup}
534 %*                                                                      *
535 %************************************************************************
536
537 \begin{code}
538 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
539
540 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
541                                         -- in the list; defaults right at the end.
542   = let
543         tidied_on_switches = foldl rm_dups [] on_switches
544                 -- The fold*l* ensures that we keep the latest switches;
545                 -- ie the ones that occur earliest in the list.
546
547         sw_tbl :: Array Int SwitchResult
548
549         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
550                         all_undefined)
551                  // defined_elems
552
553         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
554
555         defined_elems = map mk_assoc_elem tidied_on_switches
556     in
557     -- (avoid some unboxing, bounds checking, and other horrible things:)
558     case sw_tbl of { Array bounds_who_needs_'em stuff ->
559     \ switch ->
560         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
561 #if __GLASGOW_HASKELL__ < 400
562           Lift v -> v
563 #else
564           (# _, v #) -> v
565 #endif
566     }
567   where
568     mk_assoc_elem k@(MaxSimplifierIterations lvl)       = (IBOX(tagOf_SimplSwitch k), SwInt lvl)
569
570     mk_assoc_elem k = (IBOX(tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
571
572     -- cannot have duplicates if we are going to use the array thing
573     rm_dups switches_so_far switch
574       = if switch `is_elem` switches_so_far
575         then switches_so_far
576         else switch : switches_so_far
577       where
578         sw `is_elem` []     = False
579         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) _EQ_ (tagOf_SimplSwitch s)
580                             || sw `is_elem` ss
581 \end{code}
582
583 Default settings for simplifier switches
584
585 \begin{code}
586 defaultSimplSwitches = [MaxSimplifierIterations         1
587                        ]
588 \end{code}
589
590 %************************************************************************
591 %*                                                                      *
592 \subsection{Misc functions for command-line options}
593 %*                                                                      *
594 %************************************************************************
595
596
597 \begin{code}
598 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
599
600 switchIsOn lookup_fn switch
601   = case (lookup_fn switch) of
602       SwBool False -> False
603       _            -> True
604
605 intSwitchSet :: (switch -> SwitchResult)
606              -> (Int -> switch)
607              -> Maybe Int
608
609 intSwitchSet lookup_fn switch
610   = case (lookup_fn (switch (panic "intSwitchSet"))) of
611       SwInt int -> Just int
612       _         -> Nothing
613 \end{code}
614
615 \begin{code}
616 startsWith, endsWith :: String -> String -> Maybe String
617
618 startsWith []     str = Just str
619 startsWith (c:cs) (s:ss)
620   = if c /= s then Nothing else startsWith cs ss
621 startsWith  _     []  = Nothing
622
623 endsWith cs ss
624   = case (startsWith (reverse cs) (reverse ss)) of
625       Nothing -> Nothing
626       Just rs -> Just (reverse rs)
627 \end{code}