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