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
22 -- Manipulating DynFlags
23 defaultDynFlags, -- DynFlags
24 dopt, -- DynFlag -> DynFlags -> Bool
25 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
26 dopt_CoreToDo, -- DynFlags -> [CoreToDo]
27 dopt_StgToDo, -- DynFlags -> [StgToDo]
28 dopt_HscLang, -- DynFlags -> HscLang
29 dopt_OutName, -- DynFlags -> String
30 getOpts, -- (DynFlags -> [a]) -> IO [a]
34 -- sets of warning opts
38 -- Output style options
43 opt_AutoSccsOnAllToplevs,
44 opt_AutoSccsOnExportedToplevs,
45 opt_AutoSccsOnIndividualCafs,
51 opt_MaxContextReductionDepth,
52 opt_IrrefutableTuples,
61 opt_LiberateCaseThreshold,
64 opt_SimplNoPreInlining,
65 opt_SimplExcessPrecision,
69 opt_UF_CreationThreshold,
71 opt_UF_FunAppDiscount,
79 opt_EnsureSplittableC,
90 #include "HsVersions.h"
92 import {-# SOURCE #-} Packages (PackageState)
93 import Constants -- Default values for some flags
95 import FastString ( FastString, mkFastString )
97 import Maybes ( firstJust )
99 import Panic ( ghcError, GhcException(UsageError) )
101 import DATA_IOREF ( IORef, readIORef )
102 import UNSAFE_IO ( unsafePerformIO )
105 %************************************************************************
107 \subsection{Command-line options}
109 %************************************************************************
111 The hsc command-line options are split into two categories:
116 Static flags are represented by top-level values of type Bool or Int,
117 for example. They therefore have the same value throughout the
120 Dynamic flags are represented by an abstract type, DynFlags, which is
121 passed into hsc by the compilation manager for every compilation.
122 Dynamic flags are those that change on a per-compilation basis,
123 perhaps because they may be present in the OPTIONS pragma at the top
126 Other flag-related blurb:
128 A list of {\em ToDo}s is things to be done in a particular part of
129 processing. A (fictitious) example for the Core-to-Core simplifier
130 might be: run the simplifier, then run the strictness analyser, then
131 run the simplifier again (three ``todos'').
133 There are three ``to-do processing centers'' at the moment. In the
134 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
135 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
136 (\tr{simplStg/SimplStg.lhs}).
138 %************************************************************************
140 \subsection{Datatypes associated with command-line options}
142 %************************************************************************
145 data CoreToDo -- These are diff core-to-core passes,
146 -- which may be invoked in any order,
147 -- as many times as you like.
149 = CoreDoSimplify -- The core-to-core simplifier.
152 -- Each run of the simplifier can take a different
153 -- set of simplifier-specific flags.
155 | CoreDoFloatOutwards FloatOutSwitches
160 | CoreDoWorkerWrapper
163 | CoreDoOldStrictness
166 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
167 -- matching this string
169 | CoreDoNothing -- useful when building up lists of these things
174 = StgDoMassageForProfiling -- should be (next to) last
175 -- There's also setStgVarInfo, but its absolute "lastness"
176 -- is so critical that it is hardwired in (no flag).
181 data SimplifierMode -- See comments in SimplMonad
185 data SimplifierSwitch
186 = MaxSimplifierIterations Int
189 data FloatOutSwitches
190 = FloatOutSw Bool -- True <=> float lambdas to top level
191 Bool -- True <=> float constants to top level,
192 -- even if they do not escape a lambda
195 %************************************************************************
197 \subsection{Dynamic command-line options}
199 %************************************************************************
212 | Opt_D_dump_inlinings
213 | Opt_D_dump_occur_anal
217 | Opt_D_dump_simpl_iterations
226 | Opt_D_dump_worker_wrapper
227 | Opt_D_dump_rn_trace
228 | Opt_D_dump_rn_stats
230 | Opt_D_dump_simpl_stats
231 | Opt_D_dump_tc_trace
232 | Opt_D_dump_if_trace
237 | Opt_D_verbose_core2core
238 | Opt_D_verbose_stg2stg
240 | Opt_D_dump_hi_diffs
241 | Opt_D_dump_minimal_imports
246 | Opt_WarnIsError -- -Werror; makes warnings fatal
247 | Opt_WarnDuplicateExports
249 | Opt_WarnIncompletePatterns
250 | Opt_WarnIncompletePatternsRecUpd
251 | Opt_WarnMissingFields
252 | Opt_WarnMissingMethods
253 | Opt_WarnMissingSigs
254 | Opt_WarnNameShadowing
255 | Opt_WarnOverlappingPatterns
256 | Opt_WarnSimplePatterns
257 | Opt_WarnTypeDefaults
258 | Opt_WarnUnusedBinds
259 | Opt_WarnUnusedImports
260 | Opt_WarnUnusedMatches
261 | Opt_WarnDeprecations
262 | Opt_WarnDodgyImports
266 | Opt_AllowOverlappingInstances
267 | Opt_AllowUndecidableInstances
268 | Opt_AllowIncoherentInstances
269 | Opt_MonomorphismRestriction
272 | Opt_PArr -- syntactic support for parallel arrays
273 | Opt_Arrows -- Arrow-notation syntax
277 | Opt_ImplicitPrelude
283 | Opt_IgnoreInterfacePragmas
284 | Opt_OmitInterfacePragmas
285 | Opt_DoLambdaEtaExpansion
289 | Opt_UnboxStrictFields
293 data DynFlags = DynFlags {
294 coreToDo :: Maybe [CoreToDo], -- reserved for use with -Ofile
295 stgToDo :: [StgToDo],
297 hscOutName :: String, -- name of the output file
298 hscStubHOutName :: String, -- name of the .stub_h output file
299 hscStubCOutName :: String, -- name of the .stub_c output file
300 extCoreName :: String, -- name of the .core output file
301 verbosity :: Int, -- verbosity level
302 optLevel :: Int, -- optimisation level
303 maxSimplIterations :: Int, -- max simplifier iterations
304 ruleCheck :: Maybe String,
305 cppFlag :: Bool, -- preprocess with cpp?
306 ppFlag :: Bool, -- preprocess with a Haskell Pp?
307 stolen_x86_regs :: Int,
308 cmdlineHcIncludes :: [String], -- -#includes
309 importPaths :: [FilePath],
311 -- options for particular phases
324 extraPkgConfs :: [FilePath],
325 -- The -package-conf flags given on the command line, in the order
328 readUserPkgConf :: Bool,
329 -- Whether or not to read the user package database
330 -- (-no-user-package-conf).
332 packageFlags :: [PackageFlag],
333 -- The -package and -hide-package flags from the command-line
336 pkgState :: PackageState,
343 = ExposePackage String
345 | IgnorePackage String
357 | cGhcWithNativeCodeGen == "YES" &&
358 (prefixMatch "i386" cTARGETPLATFORM ||
359 prefixMatch "sparc" cTARGETPLATFORM ||
360 prefixMatch "powerpc" cTARGETPLATFORM) = HscAsm
363 defaultDynFlags = DynFlags {
364 coreToDo = Nothing, stgToDo = [],
365 hscLang = defaultHscLang,
367 hscStubHOutName = "", hscStubCOutName = "",
371 maxSimplIterations = 4,
376 cmdlineHcIncludes = [],
390 readUserPkgConf = True,
392 pkgState = error "pkgState",
396 Opt_MonomorphismRestriction,
398 -- Generating the helper-functions for
399 -- generics is now on by default
401 -- strictness is on by default, but this only
403 Opt_CSE, -- similarly for CSE.
404 Opt_FullLaziness, -- ...and for full laziness
406 Opt_DoLambdaEtaExpansion,
407 -- This one is important for a tiresome reason:
408 -- we want to make sure that the bindings for data
409 -- constructors are eta-expanded. This is probably
410 -- a good thing anyway, but it seems fragile.
412 -- and the default no-optimisation options:
413 Opt_IgnoreInterfacePragmas,
414 Opt_OmitInterfacePragmas
416 ] ++ standardWarnings
422 0 | print errors & warnings only
423 1 | minimal verbosity: print "compiling M ... done." for each module.
424 2 | equivalent to -dshow-passes
425 3 | equivalent to existing "ghc -v"
426 4 | "ghc -v -ddump-most"
427 5 | "ghc -v -ddump-all"
430 dopt :: DynFlag -> DynFlags -> Bool
431 dopt f dflags = f `elem` (flags dflags)
433 dopt_CoreToDo :: DynFlags -> Maybe [CoreToDo]
434 dopt_CoreToDo = coreToDo
436 dopt_StgToDo :: DynFlags -> [StgToDo]
437 dopt_StgToDo = stgToDo
439 dopt_OutName :: DynFlags -> String
440 dopt_OutName = hscOutName
442 dopt_HscLang :: DynFlags -> HscLang
443 dopt_HscLang = hscLang
445 dopt_set :: DynFlags -> DynFlag -> DynFlags
446 dopt_set dfs f = dfs{ flags = f : flags dfs }
448 dopt_unset :: DynFlags -> DynFlag -> DynFlags
449 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
451 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
452 -- We add to the options from the front, so we need to reverse the list
453 getOpts dflags opts = reverse (opts dflags)
456 | verbosity dflags >= 3 = "-v"
459 -----------------------------------------------------------------------------
460 -- Setting the optimisation level
464 then dfs2{ hscLang = HscC, optLevel = n } -- turn on -fvia-C with -O
465 else dfs2{ optLevel = n }
467 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
468 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
471 | n == 0 = opt_0_dopts
472 | otherwise = opt_1_dopts
475 | n == 0 = opt_1_dopts
476 | otherwise = opt_0_dopts
479 Opt_IgnoreInterfacePragmas,
480 Opt_OmitInterfacePragmas
489 -- Core-to-core phases:
491 buildCoreToDo :: DynFlags -> [CoreToDo]
492 buildCoreToDo dflags = core_todo
494 opt_level = optLevel dflags
495 max_iter = maxSimplIterations dflags
496 strictness = dopt Opt_Strictness dflags
497 full_laziness = dopt Opt_FullLaziness dflags
498 cse = dopt Opt_CSE dflags
499 rule_check = ruleCheck dflags
502 if opt_level == 0 then
504 CoreDoSimplify (SimplPhase 0) [
505 MaxSimplifierIterations max_iter
509 else {- opt_level >= 1 -} [
511 -- initial simplify: mk specialiser happy: minimum effort please
512 CoreDoSimplify SimplGently [
514 -- Don't inline anything till full laziness has bitten
515 -- In particular, inlining wrappers inhibits floating
516 -- e.g. ...(case f x of ...)...
517 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
518 -- ==> ...(case x of I# x# -> case fw x# of ...)...
519 -- and now the redex (f x) isn't floatable any more
520 -- Similarly, don't apply any rules until after full
521 -- laziness. Notably, list fusion can prevent floating.
524 -- Don't do case-of-case transformations.
525 -- This makes full laziness work better
526 MaxSimplifierIterations max_iter
529 -- Specialisation is best done before full laziness
530 -- so that overloaded functions have all their dictionary lambdas manifest
533 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
538 CoreDoSimplify (SimplPhase 2) [
539 -- Want to run with inline phase 2 after the specialiser to give
540 -- maximum chance for fusion to work before we inline build/augment
541 -- in phase 1. This made a difference in 'ansi' where an
542 -- overloaded function wasn't inlined till too late.
543 MaxSimplifierIterations max_iter
545 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
547 CoreDoSimplify (SimplPhase 1) [
548 -- Need inline-phase2 here so that build/augment get
549 -- inlined. I found that spectral/hartel/genfft lost some useful
550 -- strictness in the function sumcode' if augment is not inlined
551 -- before strictness analysis runs
552 MaxSimplifierIterations max_iter
554 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
556 CoreDoSimplify (SimplPhase 0) [
557 -- Phase 0: allow all Ids to be inlined now
558 -- This gets foldr inlined before strictness analysis
560 MaxSimplifierIterations 3
561 -- At least 3 iterations because otherwise we land up with
562 -- huge dead expressions because of an infelicity in the
564 -- let k = BIG in foldr k z xs
565 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
566 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
570 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
572 #ifdef OLD_STRICTNESS
575 if strictness then CoreDoStrictness else CoreDoNothing,
579 CoreDoSimplify (SimplPhase 0) [
580 MaxSimplifierIterations max_iter
583 if full_laziness then
584 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
585 True) -- Float constants
587 -- nofib/spectral/hartel/wang doubles in speed if you
588 -- do full laziness late in the day. It only happens
589 -- after fusion and other stuff, so the early pass doesn't
590 -- catch it. For the record, the redex is
591 -- f_el22 (f_el21 r_midblock)
594 -- We want CSE to follow the final full-laziness pass, because it may
595 -- succeed in commoning up things floated out by full laziness.
596 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
598 if cse then CoreCSE else CoreDoNothing,
602 -- Case-liberation for -O2. This should be after
603 -- strictness analysis and the simplification which follows it.
605 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
607 if opt_level >= 2 then
611 if opt_level >= 2 then
616 -- Final clean-up simplification:
617 CoreDoSimplify (SimplPhase 0) [
618 MaxSimplifierIterations max_iter
623 %************************************************************************
625 \subsection{Warnings}
627 %************************************************************************
631 = [ Opt_WarnDeprecations,
632 Opt_WarnOverlappingPatterns,
633 Opt_WarnMissingFields,
634 Opt_WarnMissingMethods,
635 Opt_WarnDuplicateExports
639 = standardWarnings ++
640 [ Opt_WarnUnusedBinds,
641 Opt_WarnUnusedMatches,
642 Opt_WarnUnusedImports,
643 Opt_WarnIncompletePatterns,
649 [ Opt_WarnTypeDefaults,
650 Opt_WarnNameShadowing,
657 %************************************************************************
659 \subsection{Classifying command-line options}
661 %************************************************************************
664 -- v_Statis_hsc_opts is here to avoid a circular dependency with
666 GLOBAL_VAR(v_Static_hsc_opts, [], [String])
668 lookUp :: FastString -> Bool
669 lookup_def_int :: String -> Int -> Int
670 lookup_def_float :: String -> Float -> Float
671 lookup_str :: String -> Maybe String
673 unpacked_static_opts = unsafePerformIO (readIORef v_Static_hsc_opts)
674 packed_static_opts = map mkFastString unpacked_static_opts
676 lookUp sw = sw `elem` packed_static_opts
678 -- (lookup_str "foo") looks for the flag -foo=X or -fooX,
679 -- and returns the string X
681 = case firstJust (map (startsWith sw) unpacked_static_opts) of
682 Just ('=' : str) -> Just str
686 lookup_def_int sw def = case (lookup_str sw) of
687 Nothing -> def -- Use default
688 Just xx -> try_read sw xx
690 lookup_def_float sw def = case (lookup_str sw) of
691 Nothing -> def -- Use default
692 Just xx -> try_read sw xx
695 try_read :: Read a => String -> String -> a
696 -- (try_read sw str) tries to read s; if it fails, it
697 -- bleats about flag sw
700 ((x,_):_) -> x -- Be forgiving: ignore trailing goop, and alternative parses
701 [] -> ghcError (UsageError ("Malformed argument " ++ str ++ " for flag " ++ sw))
702 -- ToDo: hack alert. We should really parse the arugments
703 -- and announce errors in a more civilised way.
707 Putting the compiler options into temporary at-files
708 may turn out to be necessary later on if we turn hsc into
709 a pure Win32 application where I think there's a command-line
710 length limit of 255. unpacked_opts understands the @ option.
712 unpacked_opts :: [String]
716 map unpackFS argv -- NOT ARGV any more: v_Static_hsc_opts
718 expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
723 %************************************************************************
725 \subsection{Static options}
727 %************************************************************************
731 opt_PprStyle_Debug = lookUp FSLIT("-dppr-debug")
732 opt_PprUserLength = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
735 opt_AutoSccsOnAllToplevs = lookUp FSLIT("-fauto-sccs-on-all-toplevs")
736 opt_AutoSccsOnExportedToplevs = lookUp FSLIT("-fauto-sccs-on-exported-toplevs")
737 opt_AutoSccsOnIndividualCafs = lookUp FSLIT("-fauto-sccs-on-individual-cafs")
738 opt_SccProfilingOn = lookUp FSLIT("-fscc-profiling")
739 opt_DoTickyProfiling = lookUp FSLIT("-fticky-ticky")
742 opt_AllStrict = lookUp FSLIT("-fall-strict")
743 opt_DictsStrict = lookUp FSLIT("-fdicts-strict")
744 opt_IrrefutableTuples = lookUp FSLIT("-firrefutable-tuples")
745 opt_MaxContextReductionDepth = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
746 opt_Parallel = lookUp FSLIT("-fparallel")
747 opt_SMP = lookUp FSLIT("-fsmp")
748 opt_Flatten = lookUp FSLIT("-fflatten")
751 opt_NoStateHack = lookUp FSLIT("-fno-state-hack")
752 opt_NoMethodSharing = lookUp FSLIT("-fno-method-sharing")
753 opt_CprOff = lookUp FSLIT("-fcpr-off")
754 opt_RulesOff = lookUp FSLIT("-frules-off")
755 -- Switch off CPR analysis in the new demand analyser
756 opt_LiberateCaseThreshold = lookup_def_int "-fliberate-case-threshold" (10::Int)
757 opt_MaxWorkerArgs = lookup_def_int "-fmax-worker-args" (10::Int)
759 opt_EmitCExternDecls = lookUp FSLIT("-femit-extern-decls")
760 opt_EnsureSplittableC = lookUp FSLIT("-fglobalise-toplev-names")
761 opt_GranMacros = lookUp FSLIT("-fgransim")
762 opt_HiVersion = read (cProjectVersionInt ++ cProjectPatchLevel) :: Int
763 opt_HistorySize = lookup_def_int "-fhistory-size" 20
764 opt_OmitBlackHoling = lookUp FSLIT("-dno-black-holing")
765 opt_RuntimeTypes = lookUp FSLIT("-fruntime-types")
767 -- Simplifier switches
768 opt_SimplNoPreInlining = lookUp FSLIT("-fno-pre-inlining")
769 -- NoPreInlining is there just to see how bad things
770 -- get if you don't do it!
771 opt_SimplExcessPrecision = lookUp FSLIT("-fexcess-precision")
774 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
775 opt_UF_UseThreshold = lookup_def_int "-funfolding-use-threshold" (8::Int) -- Discounts can be big
776 opt_UF_FunAppDiscount = lookup_def_int "-funfolding-fun-discount" (6::Int) -- It's great to inline a fn
777 opt_UF_KeenessFactor = lookup_def_float "-funfolding-keeness-factor" (1.5::Float)
778 opt_UF_UpdateInPlace = lookUp FSLIT("-funfolding-update-in-place")
780 opt_UF_DearOp = ( 4 :: Int)
782 opt_Static = lookUp FSLIT("-static")
783 opt_Unregisterised = lookUp FSLIT("-funregisterised")
784 opt_EmitExternalCore = lookUp FSLIT("-fext-core")
786 -- Include full span info in error messages, instead of just the start position.
787 opt_ErrorSpans = lookUp FSLIT("-ferror-spans")
789 opt_PIC = lookUp FSLIT("-fPIC")
792 %************************************************************************
794 \subsection{List of static hsc flags}
796 %************************************************************************
801 "fauto-sccs-on-all-toplevs",
802 "fauto-sccs-on-exported-toplevs",
803 "fauto-sccs-on-individual-cafs",
804 "fauto-sccs-on-dicts",
809 "firrefutable-tuples",
815 "femit-extern-decls",
816 "fglobalise-toplev-names",
818 "fno-hi-version-check",
820 "fno-method-sharing",
825 "funfolding-update-in-place",
835 || any (flip prefixMatch f) [
837 "fliberate-case-threshold",
840 "funfolding-creation-threshold",
841 "funfolding-use-threshold",
842 "funfolding-fun-discount",
843 "funfolding-keeness-factor"
847 %************************************************************************
849 \subsection{Misc functions for command-line options}
851 %************************************************************************
856 startsWith :: String -> String -> Maybe String
857 -- startsWith pfx (pfx++rest) = Just rest
859 startsWith [] str = Just str
860 startsWith (c:cs) (s:ss)
861 = if c /= s then Nothing else startsWith cs ss
862 startsWith _ [] = Nothing
864 endsWith :: String -> String -> Maybe String
866 = case (startsWith (reverse cs) (reverse ss)) of
868 Just rs -> Just (reverse rs)