1 -----------------------------------------------------------------------------
5 -- Most flags are dynamic flags, which means they can change from
6 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
7 -- multi-session GHC each session can be using different dynamic
8 -- flags. Dynamic flags can also be set at the prompt in GHCi.
10 -- (c) The University of Glasgow 2005
12 -----------------------------------------------------------------------------
19 GhcMode(..), isOneShot,
20 GhcLink(..), isNoLink,
24 -- Configuration of the core-to-core and stg-to-stg phases
28 SimplifierMode(..), FloatOutSwitches(..),
29 getCoreToDo, getStgToDo,
31 -- Manipulating DynFlags
32 defaultDynFlags, -- DynFlags
33 initDynFlags, -- DynFlags -> IO DynFlags
35 dopt, -- DynFlag -> DynFlags -> Bool
36 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
37 getOpts, -- (DynFlags -> [a]) -> IO [a]
47 machdepCCOpts, picCCOpts,
50 #include "HsVersions.h"
52 import Module ( Module, mkModule )
53 import PrelNames ( mAIN )
54 import StaticFlags ( opt_Static, opt_PIC,
55 WayName(..), v_Ways, v_Build_tag, v_RTS_Build_tag )
56 import {-# SOURCE #-} Packages (PackageState)
57 import DriverPhases ( Phase(..), phaseInputExt )
60 import Panic ( panic, GhcException(..) )
61 import Util ( notNull, splitLongestPrefix, split, normalisePath )
62 import SrcLoc ( SrcSpan )
64 import DATA_IOREF ( readIORef )
65 import EXCEPTION ( throwDyn )
67 #ifdef mingw32_TARGET_OS
68 import Data.List ( isPrefixOf )
70 import Maybe ( fromJust )
71 import Char ( isDigit, isUpper )
73 import System.IO ( hPutStrLn, stderr )
74 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
76 -- -----------------------------------------------------------------------------
89 | Opt_D_dump_inlinings
90 | Opt_D_dump_occur_anal
94 | Opt_D_dump_simpl_iterations
103 | Opt_D_dump_worker_wrapper
104 | Opt_D_dump_rn_trace
105 | Opt_D_dump_rn_stats
107 | Opt_D_dump_simpl_stats
108 | Opt_D_dump_tc_trace
109 | Opt_D_dump_if_trace
114 | Opt_D_verbose_core2core
115 | Opt_D_verbose_stg2stg
117 | Opt_D_dump_hi_diffs
118 | Opt_D_dump_minimal_imports
119 | Opt_D_faststring_stats
124 | Opt_WarnIsError -- -Werror; makes warnings fatal
125 | Opt_WarnDuplicateExports
127 | Opt_WarnIncompletePatterns
128 | Opt_WarnIncompletePatternsRecUpd
129 | Opt_WarnMissingFields
130 | Opt_WarnMissingMethods
131 | Opt_WarnMissingSigs
132 | Opt_WarnNameShadowing
133 | Opt_WarnOverlappingPatterns
134 | Opt_WarnSimplePatterns
135 | Opt_WarnTypeDefaults
136 | Opt_WarnUnusedBinds
137 | Opt_WarnUnusedImports
138 | Opt_WarnUnusedMatches
139 | Opt_WarnDeprecations
140 | Opt_WarnDodgyImports
144 | Opt_AllowOverlappingInstances
145 | Opt_AllowUndecidableInstances
146 | Opt_AllowIncoherentInstances
147 | Opt_MonomorphismRestriction
150 | Opt_PArr -- syntactic support for parallel arrays
151 | Opt_Arrows -- Arrow-notation syntax
155 | Opt_ImplicitPrelude
156 | Opt_ScopedTypeVariables
163 | Opt_IgnoreInterfacePragmas
164 | Opt_OmitInterfacePragmas
165 | Opt_DoLambdaEtaExpansion
169 | Opt_UnboxStrictFields
178 | Opt_ExcessPrecision
179 | Opt_ReadUserPackageConf
183 | Opt_HideAllPackages
194 data DynFlags = DynFlags {
197 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
198 stgToDo :: Maybe [StgToDo], -- similarly
199 hscTarget :: HscTarget,
200 hscOutName :: String, -- name of the output file
201 extCoreName :: String, -- name of the .core output file
202 verbosity :: Int, -- verbosity level
203 optLevel :: Int, -- optimisation level
204 maxSimplIterations :: Int, -- max simplifier iterations
205 ruleCheck :: Maybe String,
206 stolen_x86_regs :: Int,
207 cmdlineHcIncludes :: [String], -- -#includes
208 importPaths :: [FilePath],
210 mainFunIs :: Maybe String,
213 wayNames :: [WayName], -- way flags from the cmd line
214 buildTag :: String, -- the global "way" (eg. "p" for prof)
215 rtsBuildTag :: String, -- the RTS "way"
218 objectDir :: Maybe String,
219 hiDir :: Maybe String,
220 stubDir :: Maybe String,
226 outputFile :: Maybe String,
227 outputHi :: Maybe String,
229 includePaths :: [String],
230 libraryPaths :: [String],
231 frameworkPaths :: [String], -- used on darwin only
232 cmdlineFrameworks :: [String], -- ditto
233 tmpDir :: String, -- no trailing '/'
235 -- options for particular phases
246 -- commands for particular phases
248 pgm_P :: (String,[Option]),
250 pgm_c :: (String,[Option]),
251 pgm_m :: (String,[Option]),
252 pgm_s :: (String,[Option]),
253 pgm_a :: (String,[Option]),
254 pgm_l :: (String,[Option]),
255 pgm_dll :: (String,[Option]),
258 extraPkgConfs :: [FilePath],
259 -- The -package-conf flags given on the command line, in the order
262 packageFlags :: [PackageFlag],
263 -- The -package and -hide-package flags from the command-line
266 pkgState :: PackageState,
272 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
285 = BatchCompile -- | @ghc --make Main@
286 | Interactive -- | @ghc --interactive@
287 | OneShot -- | @ghc -c Foo.hs@
288 | JustTypecheck -- | Development environemnts, refactorer, etc.
292 isOneShot :: GhcMode -> Bool
293 isOneShot OneShot = True
294 isOneShot _other = False
296 data GhcLink -- What to do in the link step, if there is one
297 = -- Only relevant for modes
298 -- DoMake and StopBefore StopLn
299 NoLink -- Don't link at all
300 | StaticLink -- Ordinary linker [the default]
301 | MkDLL -- Make a DLL
303 isNoLink :: GhcLink -> Bool
304 isNoLink NoLink = True
305 isNoLink other = False
308 = ExposePackage String
310 | IgnorePackage String
313 | cGhcWithNativeCodeGen == "YES" = HscAsm
316 initDynFlags dflags = do
317 -- someday these will be dynamic flags
318 ways <- readIORef v_Ways
319 build_tag <- readIORef v_Build_tag
320 rts_build_tag <- readIORef v_RTS_Build_tag
323 buildTag = build_tag,
324 rtsBuildTag = rts_build_tag
330 ghcLink = StaticLink,
333 hscTarget = defaultHscTarget,
338 maxSimplIterations = 4,
341 cmdlineHcIncludes = [],
346 wayNames = panic "ways",
347 buildTag = panic "buildTag",
348 rtsBuildTag = panic "rtsBuildTag",
354 objectSuf = phaseInputExt StopLn,
355 hcSuf = phaseInputExt HCc,
358 outputFile = Nothing,
363 cmdlineFrameworks = [],
364 tmpDir = cDEFAULT_TMPDIR,
376 pgm_L = panic "pgm_L",
377 pgm_P = panic "pgm_P",
378 pgm_F = panic "pgm_F",
379 pgm_c = panic "pgm_c",
380 pgm_m = panic "pgm_m",
381 pgm_s = panic "pgm_s",
382 pgm_a = panic "pgm_a",
383 pgm_l = panic "pgm_l",
384 pgm_dll = panic "pgm_mkdll",
388 pkgState = panic "pkgState",
392 Opt_ReadUserPackageConf,
395 Opt_MonomorphismRestriction,
397 -- strictness is on by default, but this only
399 Opt_CSE, -- similarly for CSE.
400 Opt_FullLaziness, -- ...and for full laziness
402 Opt_DoLambdaEtaExpansion,
403 -- This one is important for a tiresome reason:
404 -- we want to make sure that the bindings for data
405 -- constructors are eta-expanded. This is probably
406 -- a good thing anyway, but it seems fragile.
411 -- and the default no-optimisation options:
412 Opt_IgnoreInterfacePragmas,
413 Opt_OmitInterfacePragmas
415 ] ++ standardWarnings,
417 log_action = \severity srcSpan style msg ->
419 SevInfo -> hPutStrLn stderr (show (msg style))
420 SevFatal -> hPutStrLn stderr (show (msg style))
421 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
427 0 | print errors & warnings only
428 1 | minimal verbosity: print "compiling M ... done." for each module.
429 2 | equivalent to -dshow-passes
430 3 | equivalent to existing "ghc -v"
431 4 | "ghc -v -ddump-most"
432 5 | "ghc -v -ddump-all"
435 dopt :: DynFlag -> DynFlags -> Bool
436 dopt f dflags = f `elem` (flags dflags)
438 dopt_set :: DynFlags -> DynFlag -> DynFlags
439 dopt_set dfs f = dfs{ flags = f : flags dfs }
441 dopt_unset :: DynFlags -> DynFlag -> DynFlags
442 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
444 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
445 getOpts dflags opts = reverse (opts dflags)
446 -- We add to the options from the front, so we need to reverse the list
448 getVerbFlag :: DynFlags -> String
450 | verbosity dflags >= 3 = "-v"
453 setObjectDir f d = d{ objectDir = f}
454 setHiDir f d = d{ hiDir = f}
455 setStubDir f d = d{ stubDir = f}
457 setObjectSuf f d = d{ objectSuf = f}
458 setHiSuf f d = d{ hiSuf = f}
459 setHcSuf f d = d{ hcSuf = f}
461 setOutputFile f d = d{ outputFile = f}
462 setOutputHi f d = d{ outputHi = f}
464 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
465 -- Config.hs should really use Option.
466 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
468 setPgmL f d = d{ pgm_L = f}
469 setPgmF f d = d{ pgm_F = f}
470 setPgmc f d = d{ pgm_c = (f,[])}
471 setPgmm f d = d{ pgm_m = (f,[])}
472 setPgms f d = d{ pgm_s = (f,[])}
473 setPgma f d = d{ pgm_a = (f,[])}
474 setPgml f d = d{ pgm_l = (f,[])}
475 setPgmdll f d = d{ pgm_dll = (f,[])}
477 addOptL f d = d{ opt_L = f : opt_L d}
478 addOptP f d = d{ opt_P = f : opt_P d}
479 addOptF f d = d{ opt_F = f : opt_F d}
480 addOptc f d = d{ opt_c = f : opt_c d}
481 addOptm f d = d{ opt_m = f : opt_m d}
482 addOpta f d = d{ opt_a = f : opt_a d}
483 addOptl f d = d{ opt_l = f : opt_l d}
484 addOptdll f d = d{ opt_dll = f : opt_dll d}
485 addOptdep f d = d{ opt_dep = f : opt_dep d}
487 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
489 -- -----------------------------------------------------------------------------
490 -- Command-line options
492 -- When invoking external tools as part of the compilation pipeline, we
493 -- pass these a sequence of options on the command-line. Rather than
494 -- just using a list of Strings, we use a type that allows us to distinguish
495 -- between filepaths and 'other stuff'. [The reason being, of course, that
496 -- this type gives us a handle on transforming filenames, and filenames only,
497 -- to whatever format they're expected to be on a particular platform.]
500 = FileOption -- an entry that _contains_ filename(s) / filepaths.
501 String -- a non-filepath prefix that shouldn't be
502 -- transformed (e.g., "/out=")
503 String -- the filepath/filename portion
506 -----------------------------------------------------------------------------
507 -- Setting the optimisation level
509 updOptLevel :: Int -> DynFlags -> DynFlags
510 -- Set dynflags appropriate to the optimisation level
513 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
514 else dfs2{ optLevel = n }
516 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
517 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
520 | n == 0 = opt_0_dopts
521 | otherwise = opt_1_dopts
524 | n == 0 = opt_1_dopts
525 | otherwise = opt_0_dopts
528 Opt_IgnoreInterfacePragmas,
529 Opt_OmitInterfacePragmas
538 -- -----------------------------------------------------------------------------
539 -- Standard sets of warning options
542 = [ Opt_WarnDeprecations,
543 Opt_WarnOverlappingPatterns,
544 Opt_WarnMissingFields,
545 Opt_WarnMissingMethods,
546 Opt_WarnDuplicateExports
550 = standardWarnings ++
551 [ Opt_WarnUnusedBinds,
552 Opt_WarnUnusedMatches,
553 Opt_WarnUnusedImports,
554 Opt_WarnIncompletePatterns,
560 [ Opt_WarnTypeDefaults,
561 Opt_WarnNameShadowing,
567 -- -----------------------------------------------------------------------------
568 -- CoreToDo: abstraction of core-to-core passes to run.
570 data CoreToDo -- These are diff core-to-core passes,
571 -- which may be invoked in any order,
572 -- as many times as you like.
574 = CoreDoSimplify -- The core-to-core simplifier.
577 -- Each run of the simplifier can take a different
578 -- set of simplifier-specific flags.
580 | CoreDoFloatOutwards FloatOutSwitches
585 | CoreDoWorkerWrapper
588 | CoreDoOldStrictness
591 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
592 -- matching this string
594 | CoreDoNothing -- useful when building up lists of these things
596 data SimplifierMode -- See comments in SimplMonad
600 data SimplifierSwitch
601 = MaxSimplifierIterations Int
604 data FloatOutSwitches
605 = FloatOutSw Bool -- True <=> float lambdas to top level
606 Bool -- True <=> float constants to top level,
607 -- even if they do not escape a lambda
610 -- The core-to-core pass ordering is derived from the DynFlags:
612 getCoreToDo :: DynFlags -> [CoreToDo]
614 | Just todo <- coreToDo dflags = todo -- set explicitly by user
615 | otherwise = core_todo
617 opt_level = optLevel dflags
618 max_iter = maxSimplIterations dflags
619 strictness = dopt Opt_Strictness dflags
620 full_laziness = dopt Opt_FullLaziness dflags
621 cse = dopt Opt_CSE dflags
622 rule_check = ruleCheck dflags
625 if opt_level == 0 then
627 CoreDoSimplify (SimplPhase 0) [
628 MaxSimplifierIterations max_iter
631 else {- opt_level >= 1 -} [
633 -- initial simplify: mk specialiser happy: minimum effort please
634 CoreDoSimplify SimplGently [
636 -- Don't inline anything till full laziness has bitten
637 -- In particular, inlining wrappers inhibits floating
638 -- e.g. ...(case f x of ...)...
639 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
640 -- ==> ...(case x of I# x# -> case fw x# of ...)...
641 -- and now the redex (f x) isn't floatable any more
642 -- Similarly, don't apply any rules until after full
643 -- laziness. Notably, list fusion can prevent floating.
646 -- Don't do case-of-case transformations.
647 -- This makes full laziness work better
648 MaxSimplifierIterations max_iter
651 -- Specialisation is best done before full laziness
652 -- so that overloaded functions have all their dictionary lambdas manifest
655 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
660 CoreDoSimplify (SimplPhase 2) [
661 -- Want to run with inline phase 2 after the specialiser to give
662 -- maximum chance for fusion to work before we inline build/augment
663 -- in phase 1. This made a difference in 'ansi' where an
664 -- overloaded function wasn't inlined till too late.
665 MaxSimplifierIterations max_iter
667 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
669 CoreDoSimplify (SimplPhase 1) [
670 -- Need inline-phase2 here so that build/augment get
671 -- inlined. I found that spectral/hartel/genfft lost some useful
672 -- strictness in the function sumcode' if augment is not inlined
673 -- before strictness analysis runs
674 MaxSimplifierIterations max_iter
676 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
678 CoreDoSimplify (SimplPhase 0) [
679 -- Phase 0: allow all Ids to be inlined now
680 -- This gets foldr inlined before strictness analysis
682 MaxSimplifierIterations 3
683 -- At least 3 iterations because otherwise we land up with
684 -- huge dead expressions because of an infelicity in the
686 -- let k = BIG in foldr k z xs
687 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
688 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
692 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
694 #ifdef OLD_STRICTNESS
697 if strictness then CoreDoStrictness else CoreDoNothing,
701 CoreDoSimplify (SimplPhase 0) [
702 MaxSimplifierIterations max_iter
705 if full_laziness then
706 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
707 True) -- Float constants
709 -- nofib/spectral/hartel/wang doubles in speed if you
710 -- do full laziness late in the day. It only happens
711 -- after fusion and other stuff, so the early pass doesn't
712 -- catch it. For the record, the redex is
713 -- f_el22 (f_el21 r_midblock)
716 -- We want CSE to follow the final full-laziness pass, because it may
717 -- succeed in commoning up things floated out by full laziness.
718 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
720 if cse then CoreCSE else CoreDoNothing,
724 -- Case-liberation for -O2. This should be after
725 -- strictness analysis and the simplification which follows it.
727 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
729 if opt_level >= 2 then
733 if opt_level >= 2 then
738 -- Final clean-up simplification:
739 CoreDoSimplify (SimplPhase 0) [
740 MaxSimplifierIterations max_iter
744 -- -----------------------------------------------------------------------------
745 -- StgToDo: abstraction of stg-to-stg passes to run.
748 = StgDoMassageForProfiling -- should be (next to) last
749 -- There's also setStgVarInfo, but its absolute "lastness"
750 -- is so critical that it is hardwired in (no flag).
753 getStgToDo :: DynFlags -> [StgToDo]
755 | Just todo <- stgToDo dflags = todo -- set explicitly by user
758 stg_stats = dopt Opt_StgStats dflags
760 todo1 = if stg_stats then [D_stg_stats] else []
762 todo2 | WayProf `elem` wayNames dflags
763 = StgDoMassageForProfiling : todo1
767 -- -----------------------------------------------------------------------------
771 allFlags = map ('-':) $
772 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
773 map ("fno-"++) flags ++
775 where ok (PrefixPred _ _) = False
777 flags = map fst fFlags
779 dynamic_flags :: [(String, OptKind DynP)]
781 ( "n" , NoArg (setDynFlag Opt_DryRun) )
782 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
783 , ( "F" , NoArg (setDynFlag Opt_Pp))
784 , ( "#include" , HasArg (addCmdlineHCInclude) )
785 , ( "v" , OptPrefix (setVerbosity) )
787 ------- Specific phases --------------------------------------------
788 , ( "pgmL" , HasArg (upd . setPgmL) )
789 , ( "pgmP" , HasArg (upd . setPgmP) )
790 , ( "pgmF" , HasArg (upd . setPgmF) )
791 , ( "pgmc" , HasArg (upd . setPgmc) )
792 , ( "pgmm" , HasArg (upd . setPgmm) )
793 , ( "pgms" , HasArg (upd . setPgms) )
794 , ( "pgma" , HasArg (upd . setPgma) )
795 , ( "pgml" , HasArg (upd . setPgml) )
796 , ( "pgmdll" , HasArg (upd . setPgmdll) )
798 , ( "optL" , HasArg (upd . addOptL) )
799 , ( "optP" , HasArg (upd . addOptP) )
800 , ( "optF" , HasArg (upd . addOptF) )
801 , ( "optc" , HasArg (upd . addOptc) )
802 , ( "optm" , HasArg (upd . addOptm) )
803 , ( "opta" , HasArg (upd . addOpta) )
804 , ( "optl" , HasArg (upd . addOptl) )
805 , ( "optdll" , HasArg (upd . addOptdll) )
806 , ( "optdep" , HasArg (upd . addOptdep) )
808 , ( "split-objs" , NoArg (if can_split
809 then setDynFlag Opt_SplitObjs
812 -------- Linking ----------------------------------------------------
813 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
814 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
815 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
817 ------- Libraries ---------------------------------------------------
818 , ( "L" , Prefix addLibraryPath )
819 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
822 ------- Frameworks --------------------------------------------------
823 -- -framework-path should really be -F ...
824 , ( "framework-path" , HasArg addFrameworkPath )
825 , ( "framework" , HasArg (upd . addCmdlineFramework) )
827 ------- Output Redirection ------------------------------------------
828 , ( "odir" , HasArg (upd . setObjectDir . Just))
829 , ( "o" , SepArg (upd . setOutputFile . Just))
830 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
831 , ( "osuf" , HasArg (upd . setObjectSuf))
832 , ( "hcsuf" , HasArg (upd . setHcSuf))
833 , ( "hisuf" , HasArg (upd . setHiSuf))
834 , ( "hidir" , HasArg (upd . setHiDir . Just))
835 , ( "tmpdir" , HasArg (upd . setTmpDir))
836 , ( "stubdir" , HasArg (upd . setStubDir . Just))
838 ------- Keeping temporary files -------------------------------------
839 , ( "keep-hc-file" , AnySuffix (\_ -> do setDynFlag Opt_KeepHcFiles
841 , ( "keep-s-file" , AnySuffix (\_ -> do setDynFlag Opt_KeepSFiles
843 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
844 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
846 ------- Miscellaneous ----------------------------------------------
847 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
848 , ( "main-is" , SepArg setMainIs )
850 ------- recompilation checker --------------------------------------
851 , ( "recomp" , NoArg (setDynFlag Opt_RecompChecking) )
852 , ( "no-recomp" , NoArg (unSetDynFlag Opt_RecompChecking) )
854 ------- Packages ----------------------------------------------------
855 , ( "package-conf" , HasArg extraPkgConf_ )
856 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
857 , ( "package-name" , HasArg ignorePackage ) -- for compatibility
858 , ( "package" , HasArg exposePackage )
859 , ( "hide-package" , HasArg hidePackage )
860 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
861 , ( "ignore-package" , HasArg ignorePackage )
862 , ( "syslib" , HasArg exposePackage ) -- for compatibility
864 ------ HsCpp opts ---------------------------------------------------
865 , ( "D", AnySuffix (upd . addOptP) )
866 , ( "U", AnySuffix (upd . addOptP) )
868 ------- Include/Import Paths ----------------------------------------
869 , ( "I" , Prefix addIncludePath)
870 , ( "i" , OptPrefix addImportPath )
872 ------ Debugging ----------------------------------------------------
873 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
875 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
876 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
877 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
878 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
879 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
880 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
881 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
882 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
883 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
884 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
885 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
886 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
887 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
888 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
889 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
890 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
891 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
892 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
893 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
894 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
895 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
896 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
897 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
898 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
899 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
900 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
901 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
902 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
903 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
904 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
905 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
906 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
907 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
908 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
909 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
910 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
911 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
912 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
913 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
914 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
915 , ( "dshow-passes", NoArg (do unSetDynFlag Opt_RecompChecking
917 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
919 ------ Machine dependant (-m<blah>) stuff ---------------------------
921 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
922 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
923 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
925 ------ Warning opts -------------------------------------------------
926 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
927 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
928 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
929 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
930 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
932 ------ Optimisation flags ------------------------------------------
933 , ( "O" , NoArg (upd (setOptLevel 1)))
934 , ( "Onot" , NoArg (upd (setOptLevel 0)))
935 , ( "O" , PrefixPred (all isDigit)
936 (\f -> upd (setOptLevel (read f))))
938 , ( "fmax-simplifier-iterations",
939 PrefixPred (all isDigit)
941 dfs{ maxSimplIterations = read n })) )
944 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
946 ------ Compiler flags -----------------------------------------------
948 , ( "fno-code", NoArg (do setTarget HscNothing
949 unSetDynFlag Opt_WriteIface))
950 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
951 , ( "fvia-c", NoArg (setTarget HscC) )
952 , ( "fvia-C", NoArg (setTarget HscC) )
953 , ( "filx", NoArg (setTarget HscILX) )
955 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
956 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
958 -- the rest of the -f* and -fno-* flags
959 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
960 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
963 -- these -f<blah> flags can all be reversed with -fno-<blah>
966 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
967 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
968 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
969 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
970 ( "warn-missing-fields", Opt_WarnMissingFields ),
971 ( "warn-missing-methods", Opt_WarnMissingMethods ),
972 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
973 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
974 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
975 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
976 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
977 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
978 ( "warn-unused-imports", Opt_WarnUnusedImports ),
979 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
980 ( "warn-deprecations", Opt_WarnDeprecations ),
981 ( "warn-orphans", Opt_WarnOrphans ),
982 ( "fi", Opt_FFI ), -- support `-ffi'...
983 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
984 ( "arrows", Opt_Arrows ), -- arrow syntax
985 ( "parr", Opt_PArr ),
987 ( "implicit-prelude", Opt_ImplicitPrelude ),
988 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
989 ( "bang-patterns", Opt_BangPatterns ),
990 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
991 ( "implicit-params", Opt_ImplicitParams ),
992 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
993 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
994 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
995 ( "generics", Opt_Generics ),
996 ( "strictness", Opt_Strictness ),
997 ( "full-laziness", Opt_FullLaziness ),
999 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1000 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1001 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1002 ( "ignore-asserts", Opt_IgnoreAsserts ),
1003 ( "do-eta-reduction", Opt_DoEtaReduction ),
1004 ( "case-merge", Opt_CaseMerge ),
1005 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1006 ( "excess-precision", Opt_ExcessPrecision ),
1007 ( "asm-mangling", Opt_DoAsmMangling ),
1008 ( "write-iface", Opt_WriteIface )
1011 glasgowExtsFlags = [
1016 Opt_ScopedTypeVariables,
1019 isFFlag f = f `elem` (map fst fFlags)
1020 getFFlag f = fromJust (lookup f fFlags)
1022 -- -----------------------------------------------------------------------------
1023 -- Parsing the dynamic flags.
1025 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1026 parseDynamicFlags dflags args = do
1027 let ((leftover,errs),dflags')
1028 = runCmdLine (processArgs dynamic_flags args) dflags
1029 when (not (null errs)) $ do
1030 throwDyn (UsageError (unlines errs))
1031 return (dflags', leftover)
1034 type DynP = CmdLineP DynFlags
1036 upd :: (DynFlags -> DynFlags) -> DynP ()
1038 dfs <- getCmdLineState
1039 putCmdLineState $! (f dfs)
1041 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1042 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1043 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1045 setDumpFlag :: DynFlag -> OptKind DynP
1046 setDumpFlag dump_flag
1047 = NoArg (unSetDynFlag Opt_RecompChecking >> setDynFlag dump_flag)
1048 -- Whenver we -ddump, switch off the recompilation checker,
1049 -- else you don't see the dump!
1051 setVerbosity "" = upd (\dfs -> dfs{ verbosity = 3 })
1053 | all isDigit n = upd (\dfs -> dfs{ verbosity = read n })
1054 | otherwise = throwDyn (UsageError "can't parse verbosity flag (-v<n>)")
1056 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1058 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1061 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1063 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1065 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1067 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
1068 -- (-fvia-C, -fasm, -filx respectively).
1069 setTarget l = upd (\dfs -> case hscTarget dfs of
1070 HscC -> dfs{ hscTarget = l }
1071 HscAsm -> dfs{ hscTarget = l }
1072 HscILX -> dfs{ hscTarget = l }
1075 setOptLevel :: Int -> DynFlags -> DynFlags
1076 setOptLevel n dflags
1077 | hscTarget dflags == HscInterpreted && n > 0
1079 -- not in IO any more, oh well:
1080 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1082 = updOptLevel n dflags
1085 setMainIs :: String -> DynP ()
1087 | not (null main_fn) -- The arg looked like "Foo.baz"
1088 = upd $ \d -> d{ mainFunIs = Just main_fn,
1089 mainModIs = mkModule main_mod }
1091 | isUpper (head main_mod) -- The arg looked like "Foo"
1092 = upd $ \d -> d{ mainModIs = mkModule main_mod }
1094 | otherwise -- The arg looked like "baz"
1095 = upd $ \d -> d{ mainFunIs = Just main_mod }
1097 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1099 -----------------------------------------------------------------------------
1100 -- Paths & Libraries
1102 -- -i on its own deletes the import paths
1103 addImportPath "" = upd (\s -> s{importPaths = []})
1104 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1108 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1111 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1113 addFrameworkPath p =
1114 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1116 split_marker = ':' -- not configurable (ToDo)
1118 splitPathList :: String -> [String]
1119 splitPathList s = filter notNull (splitUp s)
1120 -- empty paths are ignored: there might be a trailing
1121 -- ':' in the initial list, for example. Empty paths can
1122 -- cause confusion when they are translated into -I options
1123 -- for passing to gcc.
1125 #ifndef mingw32_TARGET_OS
1126 splitUp xs = split split_marker xs
1128 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1130 -- That is, if "foo:bar:baz" is used, this interpreted as
1131 -- consisting of three entries, 'foo', 'bar', 'baz'.
1132 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1133 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1135 -- Notice that no attempt is made to fully replace the 'standard'
1136 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1137 -- that this will cause too much breakage for users & ':' will
1138 -- work fine even with DOS paths, if you're not insisting on being silly.
1141 splitUp (x:':':div:xs) | div `elem` dir_markers
1142 = ((x:':':div:p): splitUp rs)
1144 (p,rs) = findNextPath xs
1145 -- we used to check for existence of the path here, but that
1146 -- required the IO monad to be threaded through the command-line
1147 -- parser which is quite inconvenient. The
1148 splitUp xs = cons p (splitUp rs)
1150 (p,rs) = findNextPath xs
1155 -- will be called either when we've consumed nought or the
1156 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1157 -- finding the next split marker.
1159 case break (`elem` split_markers) xs of
1160 (p, d:ds) -> (p, ds)
1163 split_markers :: [Char]
1164 split_markers = [':', ';']
1166 dir_markers :: [Char]
1167 dir_markers = ['/', '\\']
1170 -- -----------------------------------------------------------------------------
1171 -- tmpDir, where we store temporary files.
1173 setTmpDir :: FilePath -> DynFlags -> DynFlags
1174 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1176 #if !defined(mingw32_HOST_OS)
1177 canonicalise p = normalisePath p
1179 -- Canonicalisation of temp path under win32 is a bit more
1180 -- involved: (a) strip trailing slash,
1181 -- (b) normalise slashes
1182 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1184 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1186 -- if we're operating under cygwin, and TMP/TEMP is of
1187 -- the form "/cygdrive/drive/path", translate this to
1188 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1189 -- understand /cygdrive paths.)
1191 | "/cygdrive/" `isPrefixOf` path =
1192 case drop (length "/cygdrive/") path of
1193 drive:xs@('/':_) -> drive:':':xs
1197 -- strip the trailing backslash (awful, but we only do this once).
1198 removeTrailingSlash path =
1205 -----------------------------------------------------------------------------
1206 -- Via-C compilation stuff
1208 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1209 [String]) -- for registerised HC compilations
1210 machdepCCOpts dflags
1211 #if alpha_TARGET_ARCH
1213 #ifdef HAVE_THREADED_RTS_SUPPORT
1217 -- For now, to suppress the gcc warning "call-clobbered
1218 -- register used for global register variable", we simply
1219 -- disable all warnings altogether using the -w flag. Oh well.
1221 #elif hppa_TARGET_ARCH
1222 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1223 -- (very nice, but too bad the HP /usr/include files don't agree.)
1224 = ( ["-D_HPUX_SOURCE"], [] )
1226 #elif m68k_TARGET_ARCH
1227 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1228 -- popping of args to routines to be explicit; if we let things
1229 -- be deferred 'til after an STGJUMP, imminent death is certain!
1231 -- -fomit-frame-pointer : *don't*
1232 -- It's better to have a6 completely tied up being a frame pointer
1233 -- rather than let GCC pick random things to do with it.
1234 -- (If we want to steal a6, then we would try to do things
1235 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1236 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1238 #elif i386_TARGET_ARCH
1239 -- -fno-defer-pop : basically the same game as for m68k
1241 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1242 -- the fp (%ebp) for our register maps.
1243 = let n_regs = stolen_x86_regs dflags
1246 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1247 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1250 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1251 -- Some gccs are configured with
1252 -- -momit-leaf-frame-pointer on by default, and it
1253 -- apparently takes precedence over
1254 -- -fomit-frame-pointer, so we disable it first here.
1255 "-mno-omit-leaf-frame-pointer",
1257 "-fomit-frame-pointer",
1258 -- we want -fno-builtin, because when gcc inlines
1259 -- built-in functions like memcpy() it tends to
1260 -- run out of registers, requiring -monly-n-regs
1262 "-DSTOLEN_X86_REGS="++show n_regs ]
1265 #elif ia64_TARGET_ARCH
1266 = ( [], ["-fomit-frame-pointer", "-G0"] )
1268 #elif x86_64_TARGET_ARCH
1269 = ( [], ["-fomit-frame-pointer",
1270 "-fno-asynchronous-unwind-tables",
1271 -- the unwind tables are unnecessary for HC code,
1272 -- and get in the way of -split-objs. Another option
1273 -- would be to throw them away in the mangler, but this
1275 "-fno-unit-at-a-time",
1276 -- unit-at-a-time doesn't do us any good, and screws
1277 -- up -split-objs by moving the split markers around.
1278 -- It's only turned on with -O2, but put it here just
1279 -- in case someone uses -optc-O2.
1281 -- calling builtins like strlen() using the FFI can
1282 -- cause gcc to run out of regs, so use the external
1286 #elif mips_TARGET_ARCH
1287 = ( ["-static"], [] )
1289 #elif sparc_TARGET_ARCH
1291 -- For now, to suppress the gcc warning "call-clobbered
1292 -- register used for global register variable", we simply
1293 -- disable all warnings altogether using the -w flag. Oh well.
1295 #elif powerpc_apple_darwin_TARGET
1297 -- Disable Apple's precompiling preprocessor. It's a great thing
1298 -- for "normal" programs, but it doesn't support register variable
1300 = ( [], ["-no-cpp-precomp"] )
1305 picCCOpts :: DynFlags -> [String]
1307 #if darwin_TARGET_OS
1308 -- Apple prefers to do things the other way round.
1309 -- PIC is on by default.
1310 -- -mdynamic-no-pic:
1311 -- Turn off PIC code generation.
1313 -- Don't generate "common" symbols - these are unwanted
1314 -- in dynamic libraries.
1319 = ["-mdynamic-no-pic"]
1320 #elif mingw32_TARGET_OS
1321 -- no -fPIC for Windows
1330 -- -----------------------------------------------------------------------------
1335 #if defined(i386_TARGET_ARCH) \
1336 || defined(x86_64_TARGET_ARCH) \
1337 || defined(alpha_TARGET_ARCH) \
1338 || defined(hppa_TARGET_ARCH) \
1339 || defined(m68k_TARGET_ARCH) \
1340 || defined(mips_TARGET_ARCH) \
1341 || defined(powerpc_TARGET_ARCH) \
1342 || defined(rs6000_TARGET_ARCH) \
1343 || defined(sparc_TARGET_ARCH)