2 % (c) The University of Glasgow, 1996-2000
4 \section[CmdLineOpts]{Things to do with command-line options}
9 CoreToDo(..), buildCoreToDo, StgToDo(..),
11 SimplifierMode(..), FloatOutSwitches(..),
14 DynFlag(..), -- needed non-abstractly by DriverFlags
21 -- Manipulating DynFlags
22 defaultDynFlags, -- DynFlags
23 dopt, -- DynFlag -> DynFlags -> Bool
24 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
25 dopt_CoreToDo, -- DynFlags -> [CoreToDo]
26 dopt_StgToDo, -- DynFlags -> [StgToDo]
27 dopt_HscLang, -- DynFlags -> HscLang
28 dopt_OutName, -- DynFlags -> String
29 getOpts, -- (DynFlags -> [a]) -> IO [a]
34 -- Manipulating the DynFlags state
35 getDynFlags, -- IO DynFlags
36 setDynFlags, -- DynFlags -> IO ()
37 updDynFlags, -- (DynFlags -> DynFlags) -> IO ()
38 dynFlag, -- (DynFlags -> a) -> IO a
39 setDynFlag, unSetDynFlag, -- DynFlag -> IO ()
40 saveDynFlags, -- IO ()
41 restoreDynFlags, -- IO DynFlags
43 -- sets of warning opts
47 -- Output style options
52 opt_AutoSccsOnAllToplevs,
53 opt_AutoSccsOnExportedToplevs,
54 opt_AutoSccsOnIndividualCafs,
60 opt_MaxContextReductionDepth,
61 opt_IrrefutableTuples,
69 opt_LiberateCaseThreshold,
72 opt_SimplNoPreInlining,
73 opt_SimplExcessPrecision,
77 opt_UF_CreationThreshold,
79 opt_UF_FunAppDiscount,
87 opt_EnsureSplittableC,
97 #include "HsVersions.h"
99 import Constants -- Default values for some flags
101 import FastString ( FastString, mkFastString )
103 import Maybes ( firstJust )
106 import DATA_IOREF ( IORef, readIORef, writeIORef )
107 import UNSAFE_IO ( unsafePerformIO )
110 %************************************************************************
112 \subsection{Command-line options}
114 %************************************************************************
116 The hsc command-line options are split into two categories:
121 Static flags are represented by top-level values of type Bool or Int,
122 for example. They therefore have the same value throughout the
125 Dynamic flags are represented by an abstract type, DynFlags, which is
126 passed into hsc by the compilation manager for every compilation.
127 Dynamic flags are those that change on a per-compilation basis,
128 perhaps because they may be present in the OPTIONS pragma at the top
131 Other flag-related blurb:
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'').
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}).
143 %************************************************************************
145 \subsection{Datatypes associated with command-line options}
147 %************************************************************************
150 data CoreToDo -- These are diff core-to-core passes,
151 -- which may be invoked in any order,
152 -- as many times as you like.
154 = CoreDoSimplify -- The core-to-core simplifier.
157 -- Each run of the simplifier can take a different
158 -- set of simplifier-specific flags.
160 | CoreDoFloatOutwards FloatOutSwitches
165 | CoreDoWorkerWrapper
168 | CoreDoOldStrictness
171 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
172 -- matching this string
174 | CoreDoNothing -- useful when building up lists of these things
179 = StgDoMassageForProfiling -- should be (next to) last
180 -- There's also setStgVarInfo, but its absolute "lastness"
181 -- is so critical that it is hardwired in (no flag).
186 data SimplifierMode -- See comments in SimplMonad
190 data SimplifierSwitch
191 = MaxSimplifierIterations Int
194 data FloatOutSwitches
195 = FloatOutSw Bool -- True <=> float lambdas to top level
196 Bool -- True <=> float constants to top level,
197 -- even if they do not escape a lambda
200 %************************************************************************
202 \subsection{Dynamic command-line options}
204 %************************************************************************
217 | Opt_D_dump_inlinings
218 | Opt_D_dump_occur_anal
223 | Opt_D_dump_simpl_iterations
232 | Opt_D_dump_worker_wrapper
233 | Opt_D_dump_rn_trace
234 | Opt_D_dump_rn_stats
236 | Opt_D_dump_simpl_stats
237 | Opt_D_dump_tc_trace
238 | Opt_D_dump_if_trace
243 | Opt_D_verbose_core2core
244 | Opt_D_verbose_stg2stg
246 | Opt_D_dump_hi_diffs
247 | Opt_D_dump_minimal_imports
251 | Opt_WarnIsError -- -Werror; makes warnings fatal
252 | Opt_WarnDuplicateExports
254 | Opt_WarnIncompletePatterns
255 | Opt_WarnMissingFields
256 | Opt_WarnMissingMethods
257 | Opt_WarnMissingSigs
258 | Opt_WarnNameShadowing
259 | Opt_WarnOverlappingPatterns
260 | Opt_WarnSimplePatterns
261 | Opt_WarnTypeDefaults
262 | Opt_WarnUnusedBinds
263 | Opt_WarnUnusedImports
264 | Opt_WarnUnusedMatches
265 | Opt_WarnDeprecations
269 | Opt_AllowOverlappingInstances
270 | Opt_AllowUndecidableInstances
271 | Opt_AllowIncoherentInstances
272 | Opt_NoMonomorphismRestriction
275 | Opt_PArr -- syntactic support for parallel arrays
276 | Opt_Arrows -- Arrow-notation syntax
280 | Opt_NoImplicitPrelude
285 | Opt_IgnoreInterfacePragmas
286 | Opt_OmitInterfacePragmas
287 | Opt_DoLambdaEtaExpansion
291 | Opt_UnboxStrictFields
295 data DynFlags = DynFlags {
296 coreToDo :: Maybe [CoreToDo], -- reserved for use with -Ofile
297 stgToDo :: [StgToDo],
299 hscOutName :: String, -- name of the output file
300 hscStubHOutName :: String, -- name of the .stub_h output file
301 hscStubCOutName :: String, -- name of the .stub_c output file
302 extCoreName :: String, -- name of the .core output file
303 verbosity :: Int, -- verbosity level
304 optLevel :: Int, -- optimisation level
305 maxSimplIterations :: Int, -- max simplifier iterations
306 ruleCheck :: Maybe String,
307 cppFlag :: Bool, -- preprocess with cpp?
308 ppFlag :: Bool, -- preprocess with a Haskell Pp?
309 stolen_x86_regs :: Int,
310 cmdlineHcIncludes :: [String], -- -#includes
312 -- options for particular phases
338 | cGhcWithNativeCodeGen == "YES" &&
339 (prefixMatch "i386" cTARGETPLATFORM ||
340 prefixMatch "sparc" cTARGETPLATFORM ||
341 prefixMatch "powerpc" cTARGETPLATFORM) = HscAsm
344 defaultDynFlags = DynFlags {
345 coreToDo = Nothing, stgToDo = [],
346 hscLang = defaultHscLang,
348 hscStubHOutName = "", hscStubCOutName = "",
352 maxSimplIterations = 4,
357 cmdlineHcIncludes = [],
370 -- Generating the helper-functions for
371 -- generics is now on by default
373 -- strictness is on by default, but this only
376 -- similarly for CSE.
377 Opt_DoLambdaEtaExpansion,
378 -- This one is important for a tiresome reason:
379 -- we want to make sure that the bindings for data
380 -- constructors are eta-expanded. This is probably
381 -- a good thing anyway, but it seems fragile.
383 -- and the default no-optimisation options:
384 Opt_IgnoreInterfacePragmas,
385 Opt_OmitInterfacePragmas
387 ] ++ standardWarnings
393 0 | print errors & warnings only
394 1 | minimal verbosity: print "compiling M ... done." for each module.
395 2 | equivalent to -dshow-passes
396 3 | equivalent to existing "ghc -v"
397 4 | "ghc -v -ddump-most"
398 5 | "ghc -v -ddump-all"
401 dopt :: DynFlag -> DynFlags -> Bool
402 dopt f dflags = f `elem` (flags dflags)
404 dopt_CoreToDo :: DynFlags -> Maybe [CoreToDo]
405 dopt_CoreToDo = coreToDo
407 dopt_StgToDo :: DynFlags -> [StgToDo]
408 dopt_StgToDo = stgToDo
410 dopt_OutName :: DynFlags -> String
411 dopt_OutName = hscOutName
413 dopt_HscLang :: DynFlags -> HscLang
414 dopt_HscLang = hscLang
416 dopt_set :: DynFlags -> DynFlag -> DynFlags
417 dopt_set dfs f = dfs{ flags = f : flags dfs }
419 dopt_unset :: DynFlags -> DynFlag -> DynFlags
420 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
422 getOpts :: (DynFlags -> [a]) -> IO [a]
423 -- We add to the options from the front, so we need to reverse the list
424 getOpts opts = dynFlag opts >>= return . reverse
426 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
427 -- (-fvia-C, -fasm, -filx respectively).
428 setLang l = updDynFlags (\ dfs -> case hscLang dfs of
429 HscC -> dfs{ hscLang = l }
430 HscAsm -> dfs{ hscLang = l }
431 HscILX -> dfs{ hscLang = l }
435 verb <- dynFlag verbosity
436 if verb >= 3 then return "-v" else return ""
438 -----------------------------------------------------------------------------
439 -- Setting the optimisation level
441 setOptLevel :: Int -> IO ()
443 = do dflags <- getDynFlags
444 if hscLang dflags == HscInterpreted && n > 0
445 then putStr "warning: -O conflicts with --interactive; -O ignored.\n"
446 else updDynFlags (setOptLevel' n)
450 then dfs2{ hscLang = HscC, optLevel = n } -- turn on -fvia-C with -O
451 else dfs2{ optLevel = n }
453 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
454 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
457 | n == 0 = opt_0_dopts
458 | otherwise = opt_1_dopts
461 | n == 0 = opt_1_dopts
462 | otherwise = opt_0_dopts
465 Opt_IgnoreInterfacePragmas,
466 Opt_OmitInterfacePragmas
475 -- Core-to-core phases:
477 buildCoreToDo :: DynFlags -> [CoreToDo]
478 buildCoreToDo dflags = core_todo
480 opt_level = optLevel dflags
481 max_iter = maxSimplIterations dflags
482 strictness = dopt Opt_Strictness dflags
483 cse = dopt Opt_CSE dflags
484 rule_check = ruleCheck dflags
487 if opt_level == 0 then
489 CoreDoSimplify (SimplPhase 0) [
490 MaxSimplifierIterations max_iter
494 else {- opt_level >= 1 -} [
496 -- initial simplify: mk specialiser happy: minimum effort please
497 CoreDoSimplify SimplGently [
499 -- Don't inline anything till full laziness has bitten
500 -- In particular, inlining wrappers inhibits floating
501 -- e.g. ...(case f x of ...)...
502 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
503 -- ==> ...(case x of I# x# -> case fw x# of ...)...
504 -- and now the redex (f x) isn't floatable any more
505 -- Similarly, don't apply any rules until after full
506 -- laziness. Notably, list fusion can prevent floating.
509 -- Don't do case-of-case transformations.
510 -- This makes full laziness work better
511 MaxSimplifierIterations max_iter
514 -- Specialisation is best done before full laziness
515 -- so that overloaded functions have all their dictionary lambdas manifest
518 CoreDoFloatOutwards (FloatOutSw False False),
521 CoreDoSimplify (SimplPhase 2) [
522 -- Want to run with inline phase 2 after the specialiser to give
523 -- maximum chance for fusion to work before we inline build/augment
524 -- in phase 1. This made a difference in 'ansi' where an
525 -- overloaded function wasn't inlined till too late.
526 MaxSimplifierIterations max_iter
528 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
530 CoreDoSimplify (SimplPhase 1) [
531 -- Need inline-phase2 here so that build/augment get
532 -- inlined. I found that spectral/hartel/genfft lost some useful
533 -- strictness in the function sumcode' if augment is not inlined
534 -- before strictness analysis runs
535 MaxSimplifierIterations max_iter
537 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
539 CoreDoSimplify (SimplPhase 0) [
540 -- Phase 0: allow all Ids to be inlined now
541 -- This gets foldr inlined before strictness analysis
543 MaxSimplifierIterations 3
544 -- At least 3 iterations because otherwise we land up with
545 -- huge dead expressions because of an infelicity in the
547 -- let k = BIG in foldr k z xs
548 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
549 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
553 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
555 #ifdef OLD_STRICTNESS
558 if strictness then CoreDoStrictness else CoreDoNothing,
562 CoreDoSimplify (SimplPhase 0) [
563 MaxSimplifierIterations max_iter
566 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
567 True), -- Float constants
568 -- nofib/spectral/hartel/wang doubles in speed if you
569 -- do full laziness late in the day. It only happens
570 -- after fusion and other stuff, so the early pass doesn't
571 -- catch it. For the record, the redex is
572 -- f_el22 (f_el21 r_midblock)
575 -- We want CSE to follow the final full-laziness pass, because it may
576 -- succeed in commoning up things floated out by full laziness.
577 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
579 if cse then CoreCSE else CoreDoNothing,
583 -- Case-liberation for -O2. This should be after
584 -- strictness analysis and the simplification which follows it.
586 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
588 if opt_level >= 2 then
592 if opt_level >= 2 then
597 -- Final clean-up simplification:
598 CoreDoSimplify (SimplPhase 0) [
599 MaxSimplifierIterations max_iter
603 -- --------------------------------------------------------------------------
604 -- Mess about with the mutable variables holding the dynamic arguments
607 -- is the "baseline" dynamic flags, initialised from
608 -- the defaults and command line options, and updated by the
609 -- ':s' command in GHCi.
612 -- is the dynamic flags for the current compilation. It is reset
613 -- to the value of v_InitDynFlags before each compilation, then
614 -- updated by reading any OPTIONS pragma in the current module.
616 GLOBAL_VAR(v_InitDynFlags, defaultDynFlags, DynFlags)
617 GLOBAL_VAR(v_DynFlags, defaultDynFlags, DynFlags)
619 setDynFlags :: DynFlags -> IO ()
620 setDynFlags dfs = writeIORef v_DynFlags dfs
622 saveDynFlags :: IO ()
623 saveDynFlags = do dfs <- readIORef v_DynFlags
624 writeIORef v_InitDynFlags dfs
626 restoreDynFlags :: IO DynFlags
627 restoreDynFlags = do dfs <- readIORef v_InitDynFlags
628 writeIORef v_DynFlags dfs
631 getDynFlags :: IO DynFlags
632 getDynFlags = readIORef v_DynFlags
634 updDynFlags :: (DynFlags -> DynFlags) -> IO ()
635 updDynFlags f = do dfs <- readIORef v_DynFlags
636 writeIORef v_DynFlags (f dfs)
638 dynFlag :: (DynFlags -> a) -> IO a
639 dynFlag f = do dflags <- readIORef v_DynFlags; return (f dflags)
641 setDynFlag, unSetDynFlag :: DynFlag -> IO ()
642 setDynFlag f = updDynFlags (\dfs -> dopt_set dfs f)
643 unSetDynFlag f = updDynFlags (\dfs -> dopt_unset dfs f)
647 %************************************************************************
649 \subsection{Warnings}
651 %************************************************************************
655 = [ Opt_WarnDeprecations,
656 Opt_WarnOverlappingPatterns,
657 Opt_WarnMissingFields,
658 Opt_WarnMissingMethods,
659 Opt_WarnDuplicateExports
663 = standardWarnings ++
664 [ Opt_WarnUnusedBinds,
665 Opt_WarnUnusedMatches,
666 Opt_WarnUnusedImports,
667 Opt_WarnIncompletePatterns,
673 [ Opt_WarnTypeDefaults,
674 Opt_WarnNameShadowing,
680 %************************************************************************
682 \subsection{Classifying command-line options}
684 %************************************************************************
687 -- v_Statis_hsc_opts is here to avoid a circular dependency with
689 GLOBAL_VAR(v_Static_hsc_opts, [], [String])
691 lookUp :: FastString -> Bool
692 lookup_int :: String -> Maybe Int
693 lookup_def_int :: String -> Int -> Int
694 lookup_def_float :: String -> Float -> Float
695 lookup_str :: String -> Maybe String
697 unpacked_static_opts = unsafePerformIO (readIORef v_Static_hsc_opts)
698 packed_static_opts = map mkFastString unpacked_static_opts
700 lookUp sw = sw `elem` packed_static_opts
702 lookup_str sw = firstJust (map (startsWith sw) unpacked_static_opts)
704 lookup_int sw = case (lookup_str sw) of
706 Just xx -> Just (read xx)
708 lookup_def_int sw def = case (lookup_str sw) of
709 Nothing -> def -- Use default
712 lookup_def_float sw def = case (lookup_str sw) of
713 Nothing -> def -- Use default
718 Putting the compiler options into temporary at-files
719 may turn out to be necessary later on if we turn hsc into
720 a pure Win32 application where I think there's a command-line
721 length limit of 255. unpacked_opts understands the @ option.
723 unpacked_opts :: [String]
727 map unpackFS argv -- NOT ARGV any more: v_Static_hsc_opts
729 expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
734 %************************************************************************
736 \subsection{Static options}
738 %************************************************************************
742 opt_PprStyle_Debug = lookUp FSLIT("-dppr-debug")
743 opt_PprUserLength = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
746 opt_AutoSccsOnAllToplevs = lookUp FSLIT("-fauto-sccs-on-all-toplevs")
747 opt_AutoSccsOnExportedToplevs = lookUp FSLIT("-fauto-sccs-on-exported-toplevs")
748 opt_AutoSccsOnIndividualCafs = lookUp FSLIT("-fauto-sccs-on-individual-cafs")
749 opt_SccProfilingOn = lookUp FSLIT("-fscc-profiling")
750 opt_DoTickyProfiling = lookUp FSLIT("-fticky-ticky")
753 opt_AllStrict = lookUp FSLIT("-fall-strict")
754 opt_DictsStrict = lookUp FSLIT("-fdicts-strict")
755 opt_IrrefutableTuples = lookUp FSLIT("-firrefutable-tuples")
756 opt_MaxContextReductionDepth = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
757 opt_Parallel = lookUp FSLIT("-fparallel")
758 opt_SMP = lookUp FSLIT("-fsmp")
759 opt_Flatten = lookUp FSLIT("-fflatten")
762 opt_NoMethodSharing = lookUp FSLIT("-fno-method-sharing")
763 opt_CprOff = lookUp FSLIT("-fcpr-off")
764 opt_RulesOff = lookUp FSLIT("-frules-off")
765 -- Switch off CPR analysis in the new demand analyser
766 opt_LiberateCaseThreshold = lookup_def_int "-fliberate-case-threshold" (10::Int)
767 opt_MaxWorkerArgs = lookup_def_int "-fmax-worker-args" (10::Int)
770 The optional '-inpackage=P' flag tells what package
771 we are compiling this module for.
772 The Prelude, for example is compiled with '-inpackage std'
774 opt_InPackage = case lookup_str "-inpackage=" of
775 Just p -> mkFastString p
776 Nothing -> FSLIT("Main") -- The package name if none is specified
778 opt_EmitCExternDecls = lookUp FSLIT("-femit-extern-decls")
779 opt_EnsureSplittableC = lookUp FSLIT("-fglobalise-toplev-names")
780 opt_GranMacros = lookUp FSLIT("-fgransim")
781 opt_HiVersion = read (cProjectVersionInt ++ cProjectPatchLevel) :: Int
782 opt_HistorySize = lookup_def_int "-fhistory-size" 20
783 opt_OmitBlackHoling = lookUp FSLIT("-dno-black-holing")
784 opt_RuntimeTypes = lookUp FSLIT("-fruntime-types")
786 -- Simplifier switches
787 opt_SimplNoPreInlining = lookUp FSLIT("-fno-pre-inlining")
788 -- NoPreInlining is there just to see how bad things
789 -- get if you don't do it!
790 opt_SimplExcessPrecision = lookUp FSLIT("-fexcess-precision")
793 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
794 opt_UF_UseThreshold = lookup_def_int "-funfolding-use-threshold" (8::Int) -- Discounts can be big
795 opt_UF_FunAppDiscount = lookup_def_int "-funfolding-fun-discount" (6::Int) -- It's great to inline a fn
796 opt_UF_KeenessFactor = lookup_def_float "-funfolding-keeness-factor" (1.5::Float)
797 opt_UF_UpdateInPlace = lookUp FSLIT("-funfolding-update-in-place")
799 opt_UF_DearOp = ( 4 :: Int)
801 opt_Static = lookUp FSLIT("-static")
802 opt_Unregisterised = lookUp FSLIT("-funregisterised")
803 opt_EmitExternalCore = lookUp FSLIT("-fext-core")
806 %************************************************************************
808 \subsection{List of static hsc flags}
810 %************************************************************************
815 "fauto-sccs-on-all-toplevs",
816 "fauto-sccs-on-exported-toplevs",
817 "fauto-sccs-on-individual-cafs",
818 "fauto-sccs-on-dicts",
823 "firrefutable-tuples",
829 "femit-extern-decls",
830 "fglobalise-toplev-names",
832 "fno-hi-version-check",
834 "fno-method-sharing",
838 "funfolding-update-in-place",
847 || any (flip prefixMatch f) [
849 "fliberate-case-threshold",
852 "funfolding-creation-threshold",
853 "funfolding-use-threshold",
854 "funfolding-fun-discount",
855 "funfolding-keeness-factor"
859 %************************************************************************
861 \subsection{Misc functions for command-line options}
863 %************************************************************************
868 startsWith :: String -> String -> Maybe String
869 -- startsWith pfx (pfx++rest) = Just rest
871 startsWith [] str = Just str
872 startsWith (c:cs) (s:ss)
873 = if c /= s then Nothing else startsWith cs ss
874 startsWith _ [] = Nothing
876 endsWith :: String -> String -> Maybe String
878 = case (startsWith (reverse cs) (reverse ss)) of
880 Just rs -> Just (reverse rs)