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