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]
46 machdepCCOpts, picCCOpts,
49 #include "HsVersions.h"
51 import Module ( Module, mkModule )
52 import PrelNames ( mAIN )
53 import StaticFlags ( opt_Static, opt_PIC,
54 WayName(..), v_Ways, v_Build_tag, v_RTS_Build_tag )
55 import {-# SOURCE #-} Packages (PackageState)
56 import DriverPhases ( Phase(..), phaseInputExt )
59 import Panic ( panic, GhcException(..) )
60 import Util ( notNull, splitLongestPrefix, split, normalisePath )
61 import SrcLoc ( SrcSpan )
63 import DATA_IOREF ( readIORef )
64 import EXCEPTION ( throwDyn )
66 #ifdef mingw32_TARGET_OS
67 import Data.List ( isPrefixOf )
69 import Maybe ( fromJust )
70 import Char ( isDigit, isUpper )
72 import System.IO ( hPutStrLn, stderr )
73 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
75 -- -----------------------------------------------------------------------------
88 | Opt_D_dump_inlinings
89 | Opt_D_dump_occur_anal
93 | Opt_D_dump_simpl_iterations
102 | Opt_D_dump_worker_wrapper
103 | Opt_D_dump_rn_trace
104 | Opt_D_dump_rn_stats
106 | Opt_D_dump_simpl_stats
107 | Opt_D_dump_tc_trace
108 | Opt_D_dump_if_trace
113 | Opt_D_verbose_core2core
114 | Opt_D_verbose_stg2stg
116 | Opt_D_dump_hi_diffs
117 | Opt_D_dump_minimal_imports
118 | Opt_D_faststring_stats
123 | Opt_WarnIsError -- -Werror; makes warnings fatal
124 | Opt_WarnDuplicateExports
126 | Opt_WarnIncompletePatterns
127 | Opt_WarnIncompletePatternsRecUpd
128 | Opt_WarnMissingFields
129 | Opt_WarnMissingMethods
130 | Opt_WarnMissingSigs
131 | Opt_WarnNameShadowing
132 | Opt_WarnOverlappingPatterns
133 | Opt_WarnSimplePatterns
134 | Opt_WarnTypeDefaults
135 | Opt_WarnUnusedBinds
136 | Opt_WarnUnusedImports
137 | Opt_WarnUnusedMatches
138 | Opt_WarnDeprecations
139 | Opt_WarnDodgyImports
143 | Opt_AllowOverlappingInstances
144 | Opt_AllowUndecidableInstances
145 | Opt_AllowIncoherentInstances
146 | Opt_MonomorphismRestriction
149 | Opt_PArr -- syntactic support for parallel arrays
150 | Opt_Arrows -- Arrow-notation syntax
154 | Opt_ImplicitPrelude
155 | Opt_ScopedTypeVariables
162 | Opt_IgnoreInterfacePragmas
163 | Opt_OmitInterfacePragmas
164 | Opt_DoLambdaEtaExpansion
168 | Opt_UnboxStrictFields
176 | Opt_ExcessPrecision
177 | Opt_ReadUserPackageConf
181 | Opt_HideAllPackages
192 data DynFlags = DynFlags {
195 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
196 stgToDo :: Maybe [StgToDo], -- similarly
197 hscTarget :: HscTarget,
198 hscOutName :: String, -- name of the output file
199 extCoreName :: String, -- name of the .core output file
200 verbosity :: Int, -- verbosity level
201 optLevel :: Int, -- optimisation level
202 maxSimplIterations :: Int, -- max simplifier iterations
203 ruleCheck :: Maybe String,
204 stolen_x86_regs :: Int,
205 cmdlineHcIncludes :: [String], -- -#includes
206 importPaths :: [FilePath],
208 mainFunIs :: Maybe String,
211 wayNames :: [WayName], -- way flags from the cmd line
212 buildTag :: String, -- the global "way" (eg. "p" for prof)
213 rtsBuildTag :: String, -- the RTS "way"
216 objectDir :: Maybe String,
217 hiDir :: Maybe String,
218 stubDir :: Maybe String,
224 outputFile :: Maybe String,
225 outputHi :: Maybe String,
227 includePaths :: [String],
228 libraryPaths :: [String],
229 frameworkPaths :: [String], -- used on darwin only
230 cmdlineFrameworks :: [String], -- ditto
231 tmpDir :: String, -- no trailing '/'
233 -- options for particular phases
244 -- commands for particular phases
246 pgm_P :: (String,[Option]),
248 pgm_c :: (String,[Option]),
249 pgm_m :: (String,[Option]),
250 pgm_s :: (String,[Option]),
251 pgm_a :: (String,[Option]),
252 pgm_l :: (String,[Option]),
253 pgm_dll :: (String,[Option]),
256 extraPkgConfs :: [FilePath],
257 -- The -package-conf flags given on the command line, in the order
260 packageFlags :: [PackageFlag],
261 -- The -package and -hide-package flags from the command-line
264 pkgState :: PackageState,
270 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
283 = BatchCompile -- | @ghc --make Main@
284 | Interactive -- | @ghc --interactive@
285 | OneShot -- | @ghc -c Foo.hs@
286 | JustTypecheck -- | Development environemnts, refactorer, etc.
290 isOneShot :: GhcMode -> Bool
291 isOneShot OneShot = True
292 isOneShot _other = False
294 data GhcLink -- What to do in the link step, if there is one
295 = -- Only relevant for modes
296 -- DoMake and StopBefore StopLn
297 NoLink -- Don't link at all
298 | StaticLink -- Ordinary linker [the default]
299 | MkDLL -- Make a DLL
301 isNoLink :: GhcLink -> Bool
302 isNoLink NoLink = True
303 isNoLink other = False
306 = ExposePackage String
308 | IgnorePackage String
311 | cGhcWithNativeCodeGen == "YES" = HscAsm
314 initDynFlags dflags = do
315 -- someday these will be dynamic flags
316 ways <- readIORef v_Ways
317 build_tag <- readIORef v_Build_tag
318 rts_build_tag <- readIORef v_RTS_Build_tag
321 buildTag = build_tag,
322 rtsBuildTag = rts_build_tag
328 ghcLink = StaticLink,
331 hscTarget = defaultHscTarget,
336 maxSimplIterations = 4,
339 cmdlineHcIncludes = [],
344 wayNames = panic "ways",
345 buildTag = panic "buildTag",
346 rtsBuildTag = panic "rtsBuildTag",
352 objectSuf = phaseInputExt StopLn,
353 hcSuf = phaseInputExt HCc,
356 outputFile = Nothing,
361 cmdlineFrameworks = [],
362 tmpDir = cDEFAULT_TMPDIR,
374 pgm_L = panic "pgm_L",
375 pgm_P = panic "pgm_P",
376 pgm_F = panic "pgm_F",
377 pgm_c = panic "pgm_c",
378 pgm_m = panic "pgm_m",
379 pgm_s = panic "pgm_s",
380 pgm_a = panic "pgm_a",
381 pgm_l = panic "pgm_l",
382 pgm_dll = panic "pgm_mkdll",
386 pkgState = panic "pkgState",
390 Opt_ReadUserPackageConf,
393 Opt_MonomorphismRestriction,
395 -- strictness is on by default, but this only
397 Opt_CSE, -- similarly for CSE.
398 Opt_FullLaziness, -- ...and for full laziness
400 Opt_DoLambdaEtaExpansion,
401 -- This one is important for a tiresome reason:
402 -- we want to make sure that the bindings for data
403 -- constructors are eta-expanded. This is probably
404 -- a good thing anyway, but it seems fragile.
408 -- and the default no-optimisation options:
409 Opt_IgnoreInterfacePragmas,
410 Opt_OmitInterfacePragmas
412 ] ++ standardWarnings,
414 log_action = \severity srcSpan style msg ->
416 SevInfo -> hPutStrLn stderr (show (msg style))
417 SevFatal -> hPutStrLn stderr (show (msg style))
418 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
424 0 | print errors & warnings only
425 1 | minimal verbosity: print "compiling M ... done." for each module.
426 2 | equivalent to -dshow-passes
427 3 | equivalent to existing "ghc -v"
428 4 | "ghc -v -ddump-most"
429 5 | "ghc -v -ddump-all"
432 dopt :: DynFlag -> DynFlags -> Bool
433 dopt f dflags = f `elem` (flags dflags)
435 dopt_set :: DynFlags -> DynFlag -> DynFlags
436 dopt_set dfs f = dfs{ flags = f : flags dfs }
438 dopt_unset :: DynFlags -> DynFlag -> DynFlags
439 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
441 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
442 getOpts dflags opts = reverse (opts dflags)
443 -- We add to the options from the front, so we need to reverse the list
445 getVerbFlag :: DynFlags -> String
447 | verbosity dflags >= 3 = "-v"
450 setObjectDir f d = d{ objectDir = f}
451 setHiDir f d = d{ hiDir = f}
452 setStubDir f d = d{ stubDir = f}
454 setObjectSuf f d = d{ objectSuf = f}
455 setHiSuf f d = d{ hiSuf = f}
456 setHcSuf f d = d{ hcSuf = f}
458 setOutputFile f d = d{ outputFile = f}
459 setOutputHi f d = d{ outputHi = f}
461 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
462 -- Config.hs should really use Option.
463 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
465 setPgmL f d = d{ pgm_L = f}
466 setPgmF f d = d{ pgm_F = f}
467 setPgmc f d = d{ pgm_c = (f,[])}
468 setPgmm f d = d{ pgm_m = (f,[])}
469 setPgms f d = d{ pgm_s = (f,[])}
470 setPgma f d = d{ pgm_a = (f,[])}
471 setPgml f d = d{ pgm_l = (f,[])}
472 setPgmdll f d = d{ pgm_dll = (f,[])}
474 addOptL f d = d{ opt_L = f : opt_L d}
475 addOptP f d = d{ opt_P = f : opt_P d}
476 addOptF f d = d{ opt_F = f : opt_F d}
477 addOptc f d = d{ opt_c = f : opt_c d}
478 addOptm f d = d{ opt_m = f : opt_m d}
479 addOpta f d = d{ opt_a = f : opt_a d}
480 addOptl f d = d{ opt_l = f : opt_l d}
481 addOptdll f d = d{ opt_dll = f : opt_dll d}
482 addOptdep f d = d{ opt_dep = f : opt_dep d}
484 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
486 -- -----------------------------------------------------------------------------
487 -- Command-line options
489 -- When invoking external tools as part of the compilation pipeline, we
490 -- pass these a sequence of options on the command-line. Rather than
491 -- just using a list of Strings, we use a type that allows us to distinguish
492 -- between filepaths and 'other stuff'. [The reason being, of course, that
493 -- this type gives us a handle on transforming filenames, and filenames only,
494 -- to whatever format they're expected to be on a particular platform.]
497 = FileOption -- an entry that _contains_ filename(s) / filepaths.
498 String -- a non-filepath prefix that shouldn't be
499 -- transformed (e.g., "/out=")
500 String -- the filepath/filename portion
503 -----------------------------------------------------------------------------
504 -- Setting the optimisation level
506 updOptLevel :: Int -> DynFlags -> DynFlags
507 -- Set dynflags appropriate to the optimisation level
510 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
511 else dfs2{ optLevel = n }
513 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
514 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
517 | n == 0 = opt_0_dopts
518 | otherwise = opt_1_dopts
521 | n == 0 = opt_1_dopts
522 | otherwise = opt_0_dopts
525 Opt_IgnoreInterfacePragmas,
526 Opt_OmitInterfacePragmas
535 -- -----------------------------------------------------------------------------
536 -- Standard sets of warning options
539 = [ Opt_WarnDeprecations,
540 Opt_WarnOverlappingPatterns,
541 Opt_WarnMissingFields,
542 Opt_WarnMissingMethods,
543 Opt_WarnDuplicateExports
547 = standardWarnings ++
548 [ Opt_WarnUnusedBinds,
549 Opt_WarnUnusedMatches,
550 Opt_WarnUnusedImports,
551 Opt_WarnIncompletePatterns,
557 [ Opt_WarnTypeDefaults,
558 Opt_WarnNameShadowing,
564 -- -----------------------------------------------------------------------------
565 -- CoreToDo: abstraction of core-to-core passes to run.
567 data CoreToDo -- These are diff core-to-core passes,
568 -- which may be invoked in any order,
569 -- as many times as you like.
571 = CoreDoSimplify -- The core-to-core simplifier.
574 -- Each run of the simplifier can take a different
575 -- set of simplifier-specific flags.
577 | CoreDoFloatOutwards FloatOutSwitches
582 | CoreDoWorkerWrapper
585 | CoreDoOldStrictness
588 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
589 -- matching this string
591 | CoreDoNothing -- useful when building up lists of these things
593 data SimplifierMode -- See comments in SimplMonad
597 data SimplifierSwitch
598 = MaxSimplifierIterations Int
601 data FloatOutSwitches
602 = FloatOutSw Bool -- True <=> float lambdas to top level
603 Bool -- True <=> float constants to top level,
604 -- even if they do not escape a lambda
607 -- The core-to-core pass ordering is derived from the DynFlags:
609 getCoreToDo :: DynFlags -> [CoreToDo]
611 | Just todo <- coreToDo dflags = todo -- set explicitly by user
612 | otherwise = core_todo
614 opt_level = optLevel dflags
615 max_iter = maxSimplIterations dflags
616 strictness = dopt Opt_Strictness dflags
617 full_laziness = dopt Opt_FullLaziness dflags
618 cse = dopt Opt_CSE dflags
619 rule_check = ruleCheck dflags
622 if opt_level == 0 then
624 CoreDoSimplify (SimplPhase 0) [
625 MaxSimplifierIterations max_iter
628 else {- opt_level >= 1 -} [
630 -- initial simplify: mk specialiser happy: minimum effort please
631 CoreDoSimplify SimplGently [
633 -- Don't inline anything till full laziness has bitten
634 -- In particular, inlining wrappers inhibits floating
635 -- e.g. ...(case f x of ...)...
636 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
637 -- ==> ...(case x of I# x# -> case fw x# of ...)...
638 -- and now the redex (f x) isn't floatable any more
639 -- Similarly, don't apply any rules until after full
640 -- laziness. Notably, list fusion can prevent floating.
643 -- Don't do case-of-case transformations.
644 -- This makes full laziness work better
645 MaxSimplifierIterations max_iter
648 -- Specialisation is best done before full laziness
649 -- so that overloaded functions have all their dictionary lambdas manifest
652 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
657 CoreDoSimplify (SimplPhase 2) [
658 -- Want to run with inline phase 2 after the specialiser to give
659 -- maximum chance for fusion to work before we inline build/augment
660 -- in phase 1. This made a difference in 'ansi' where an
661 -- overloaded function wasn't inlined till too late.
662 MaxSimplifierIterations max_iter
664 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
666 CoreDoSimplify (SimplPhase 1) [
667 -- Need inline-phase2 here so that build/augment get
668 -- inlined. I found that spectral/hartel/genfft lost some useful
669 -- strictness in the function sumcode' if augment is not inlined
670 -- before strictness analysis runs
671 MaxSimplifierIterations max_iter
673 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
675 CoreDoSimplify (SimplPhase 0) [
676 -- Phase 0: allow all Ids to be inlined now
677 -- This gets foldr inlined before strictness analysis
679 MaxSimplifierIterations 3
680 -- At least 3 iterations because otherwise we land up with
681 -- huge dead expressions because of an infelicity in the
683 -- let k = BIG in foldr k z xs
684 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
685 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
689 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
691 #ifdef OLD_STRICTNESS
694 if strictness then CoreDoStrictness else CoreDoNothing,
698 CoreDoSimplify (SimplPhase 0) [
699 MaxSimplifierIterations max_iter
702 if full_laziness then
703 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
704 True) -- Float constants
706 -- nofib/spectral/hartel/wang doubles in speed if you
707 -- do full laziness late in the day. It only happens
708 -- after fusion and other stuff, so the early pass doesn't
709 -- catch it. For the record, the redex is
710 -- f_el22 (f_el21 r_midblock)
713 -- We want CSE to follow the final full-laziness pass, because it may
714 -- succeed in commoning up things floated out by full laziness.
715 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
717 if cse then CoreCSE else CoreDoNothing,
721 -- Case-liberation for -O2. This should be after
722 -- strictness analysis and the simplification which follows it.
724 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
726 if opt_level >= 2 then
730 if opt_level >= 2 then
735 -- Final clean-up simplification:
736 CoreDoSimplify (SimplPhase 0) [
737 MaxSimplifierIterations max_iter
741 -- -----------------------------------------------------------------------------
742 -- StgToDo: abstraction of stg-to-stg passes to run.
745 = StgDoMassageForProfiling -- should be (next to) last
746 -- There's also setStgVarInfo, but its absolute "lastness"
747 -- is so critical that it is hardwired in (no flag).
750 getStgToDo :: DynFlags -> [StgToDo]
752 | Just todo <- stgToDo dflags = todo -- set explicitly by user
755 stg_stats = dopt Opt_StgStats dflags
757 todo1 = if stg_stats then [D_stg_stats] else []
759 todo2 | WayProf `elem` wayNames dflags
760 = StgDoMassageForProfiling : todo1
764 -- -----------------------------------------------------------------------------
767 dynamic_flags :: [(String, OptKind DynP)]
769 ( "n" , NoArg (setDynFlag Opt_DryRun) )
770 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
771 , ( "F" , NoArg (setDynFlag Opt_Pp))
772 , ( "#include" , HasArg (addCmdlineHCInclude) )
773 , ( "v" , OptPrefix (setVerbosity) )
775 ------- Specific phases --------------------------------------------
776 , ( "pgmL" , HasArg (upd . setPgmL) )
777 , ( "pgmP" , HasArg (upd . setPgmP) )
778 , ( "pgmF" , HasArg (upd . setPgmF) )
779 , ( "pgmc" , HasArg (upd . setPgmc) )
780 , ( "pgmm" , HasArg (upd . setPgmm) )
781 , ( "pgms" , HasArg (upd . setPgms) )
782 , ( "pgma" , HasArg (upd . setPgma) )
783 , ( "pgml" , HasArg (upd . setPgml) )
784 , ( "pgmdll" , HasArg (upd . setPgmdll) )
786 , ( "optL" , HasArg (upd . addOptL) )
787 , ( "optP" , HasArg (upd . addOptP) )
788 , ( "optF" , HasArg (upd . addOptF) )
789 , ( "optc" , HasArg (upd . addOptc) )
790 , ( "optm" , HasArg (upd . addOptm) )
791 , ( "opta" , HasArg (upd . addOpta) )
792 , ( "optl" , HasArg (upd . addOptl) )
793 , ( "optdll" , HasArg (upd . addOptdll) )
794 , ( "optdep" , HasArg (upd . addOptdep) )
796 , ( "split-objs" , NoArg (if can_split
797 then setDynFlag Opt_SplitObjs
800 -------- Linking ----------------------------------------------------
801 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
802 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
803 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
805 ------- Libraries ---------------------------------------------------
806 , ( "L" , Prefix addLibraryPath )
807 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
810 ------- Frameworks --------------------------------------------------
811 -- -framework-path should really be -F ...
812 , ( "framework-path" , HasArg addFrameworkPath )
813 , ( "framework" , HasArg (upd . addCmdlineFramework) )
815 ------- Output Redirection ------------------------------------------
816 , ( "odir" , HasArg (upd . setObjectDir . Just))
817 , ( "o" , SepArg (upd . setOutputFile . Just))
818 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
819 , ( "osuf" , HasArg (upd . setObjectSuf))
820 , ( "hcsuf" , HasArg (upd . setHcSuf))
821 , ( "hisuf" , HasArg (upd . setHiSuf))
822 , ( "hidir" , HasArg (upd . setHiDir . Just))
823 , ( "tmpdir" , HasArg (upd . setTmpDir))
824 , ( "stubdir" , HasArg (upd . setStubDir . Just))
826 ------- Keeping temporary files -------------------------------------
827 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
828 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
829 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
830 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
832 ------- Miscellaneous ----------------------------------------------
833 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
834 , ( "main-is" , SepArg setMainIs )
836 ------- recompilation checker --------------------------------------
837 , ( "recomp" , NoArg (setDynFlag Opt_RecompChecking) )
838 , ( "no-recomp" , NoArg (unSetDynFlag Opt_RecompChecking) )
840 ------- Packages ----------------------------------------------------
841 , ( "package-conf" , HasArg extraPkgConf_ )
842 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
843 , ( "package-name" , HasArg ignorePackage ) -- for compatibility
844 , ( "package" , HasArg exposePackage )
845 , ( "hide-package" , HasArg hidePackage )
846 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
847 , ( "ignore-package" , HasArg ignorePackage )
848 , ( "syslib" , HasArg exposePackage ) -- for compatibility
850 ------ HsCpp opts ---------------------------------------------------
851 , ( "D", AnySuffix (upd . addOptP) )
852 , ( "U", AnySuffix (upd . addOptP) )
854 ------- Include/Import Paths ----------------------------------------
855 , ( "I" , Prefix addIncludePath)
856 , ( "i" , OptPrefix addImportPath )
858 ------ Debugging ----------------------------------------------------
859 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
861 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
862 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
863 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
864 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
865 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
866 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
867 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
868 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
869 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
870 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
871 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
872 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
873 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
874 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
875 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
876 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
877 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
878 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
879 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
880 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
881 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
882 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
883 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
884 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
885 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
886 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
887 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
888 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
889 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
890 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
891 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
892 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
893 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
894 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
895 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
896 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
897 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
898 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
899 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
900 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
901 , ( "dshow-passes", NoArg (do unSetDynFlag Opt_RecompChecking
903 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
905 ------ Machine dependant (-m<blah>) stuff ---------------------------
907 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
908 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
909 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
911 ------ Warning opts -------------------------------------------------
912 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
913 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
914 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
915 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
916 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
918 ------ Optimisation flags ------------------------------------------
919 , ( "O" , NoArg (upd (setOptLevel 1)))
920 , ( "Onot" , NoArg (upd (setOptLevel 0)))
921 , ( "O" , PrefixPred (all isDigit)
922 (\f -> upd (setOptLevel (read f))))
924 , ( "fmax-simplifier-iterations",
925 PrefixPred (all isDigit)
927 dfs{ maxSimplIterations = read n })) )
930 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
932 ------ Compiler flags -----------------------------------------------
934 , ( "fno-code", NoArg (setTarget HscNothing))
935 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
936 , ( "fvia-c", NoArg (setTarget HscC) )
937 , ( "fvia-C", NoArg (setTarget HscC) )
938 , ( "filx", NoArg (setTarget HscILX) )
940 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
941 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
943 -- the rest of the -f* and -fno-* flags
944 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
945 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
948 -- these -f<blah> flags can all be reversed with -fno-<blah>
951 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
952 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
953 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
954 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
955 ( "warn-missing-fields", Opt_WarnMissingFields ),
956 ( "warn-missing-methods", Opt_WarnMissingMethods ),
957 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
958 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
959 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
960 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
961 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
962 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
963 ( "warn-unused-imports", Opt_WarnUnusedImports ),
964 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
965 ( "warn-deprecations", Opt_WarnDeprecations ),
966 ( "warn-orphans", Opt_WarnOrphans ),
967 ( "fi", Opt_FFI ), -- support `-ffi'...
968 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
969 ( "arrows", Opt_Arrows ), -- arrow syntax
970 ( "parr", Opt_PArr ),
972 ( "implicit-prelude", Opt_ImplicitPrelude ),
973 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
974 ( "bang-patterns", Opt_BangPatterns ),
975 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
976 ( "implicit-params", Opt_ImplicitParams ),
977 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
978 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
979 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
980 ( "generics", Opt_Generics ),
981 ( "strictness", Opt_Strictness ),
982 ( "full-laziness", Opt_FullLaziness ),
984 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
985 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
986 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
987 ( "ignore-asserts", Opt_IgnoreAsserts ),
988 ( "do-eta-reduction", Opt_DoEtaReduction ),
989 ( "case-merge", Opt_CaseMerge ),
990 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
991 ( "excess-precision", Opt_ExcessPrecision ),
992 ( "asm-mangling", Opt_DoAsmMangling )
1000 Opt_ScopedTypeVariables,
1003 isFFlag f = f `elem` (map fst fFlags)
1004 getFFlag f = fromJust (lookup f fFlags)
1006 -- -----------------------------------------------------------------------------
1007 -- Parsing the dynamic flags.
1009 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1010 parseDynamicFlags dflags args = do
1011 let ((leftover,errs),dflags')
1012 = runCmdLine (processArgs dynamic_flags args) dflags
1013 when (not (null errs)) $ do
1014 throwDyn (UsageError (unlines errs))
1015 return (dflags', leftover)
1018 type DynP = CmdLineP DynFlags
1020 upd :: (DynFlags -> DynFlags) -> DynP ()
1022 dfs <- getCmdLineState
1023 putCmdLineState $! (f dfs)
1025 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1026 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1027 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1029 setDumpFlag :: DynFlag -> OptKind DynP
1030 setDumpFlag dump_flag
1031 = NoArg (unSetDynFlag Opt_RecompChecking >> setDynFlag dump_flag)
1032 -- Whenver we -ddump, switch off the recompilation checker,
1033 -- else you don't see the dump!
1035 setVerbosity "" = upd (\dfs -> dfs{ verbosity = 3 })
1037 | all isDigit n = upd (\dfs -> dfs{ verbosity = read n })
1038 | otherwise = throwDyn (UsageError "can't parse verbosity flag (-v<n>)")
1040 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1042 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1045 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1047 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1049 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1051 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
1052 -- (-fvia-C, -fasm, -filx respectively).
1053 setTarget l = upd (\dfs -> case hscTarget dfs of
1054 HscC -> dfs{ hscTarget = l }
1055 HscAsm -> dfs{ hscTarget = l }
1056 HscILX -> dfs{ hscTarget = l }
1059 setOptLevel :: Int -> DynFlags -> DynFlags
1060 setOptLevel n dflags
1061 | hscTarget dflags == HscInterpreted && n > 0
1063 -- not in IO any more, oh well:
1064 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1066 = updOptLevel n dflags
1069 setMainIs :: String -> DynP ()
1071 | not (null main_fn) -- The arg looked like "Foo.baz"
1072 = upd $ \d -> d{ mainFunIs = Just main_fn,
1073 mainModIs = mkModule main_mod }
1075 | isUpper (head main_mod) -- The arg looked like "Foo"
1076 = upd $ \d -> d{ mainModIs = mkModule main_mod }
1078 | otherwise -- The arg looked like "baz"
1079 = upd $ \d -> d{ mainFunIs = Just main_mod }
1081 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1083 -----------------------------------------------------------------------------
1084 -- Paths & Libraries
1086 -- -i on its own deletes the import paths
1087 addImportPath "" = upd (\s -> s{importPaths = []})
1088 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1092 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1095 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1097 addFrameworkPath p =
1098 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1100 split_marker = ':' -- not configurable (ToDo)
1102 splitPathList :: String -> [String]
1103 splitPathList s = filter notNull (splitUp s)
1104 -- empty paths are ignored: there might be a trailing
1105 -- ':' in the initial list, for example. Empty paths can
1106 -- cause confusion when they are translated into -I options
1107 -- for passing to gcc.
1109 #ifndef mingw32_TARGET_OS
1110 splitUp xs = split split_marker xs
1112 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1114 -- That is, if "foo:bar:baz" is used, this interpreted as
1115 -- consisting of three entries, 'foo', 'bar', 'baz'.
1116 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1117 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1119 -- Notice that no attempt is made to fully replace the 'standard'
1120 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1121 -- that this will cause too much breakage for users & ':' will
1122 -- work fine even with DOS paths, if you're not insisting on being silly.
1125 splitUp (x:':':div:xs) | div `elem` dir_markers
1126 = ((x:':':div:p): splitUp rs)
1128 (p,rs) = findNextPath xs
1129 -- we used to check for existence of the path here, but that
1130 -- required the IO monad to be threaded through the command-line
1131 -- parser which is quite inconvenient. The
1132 splitUp xs = cons p (splitUp rs)
1134 (p,rs) = findNextPath xs
1139 -- will be called either when we've consumed nought or the
1140 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1141 -- finding the next split marker.
1143 case break (`elem` split_markers) xs of
1144 (p, d:ds) -> (p, ds)
1147 split_markers :: [Char]
1148 split_markers = [':', ';']
1150 dir_markers :: [Char]
1151 dir_markers = ['/', '\\']
1154 -- -----------------------------------------------------------------------------
1155 -- tmpDir, where we store temporary files.
1157 setTmpDir :: FilePath -> DynFlags -> DynFlags
1158 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1160 #if !defined(mingw32_HOST_OS)
1161 canonicalise p = normalisePath p
1163 -- Canonicalisation of temp path under win32 is a bit more
1164 -- involved: (a) strip trailing slash,
1165 -- (b) normalise slashes
1166 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1168 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1170 -- if we're operating under cygwin, and TMP/TEMP is of
1171 -- the form "/cygdrive/drive/path", translate this to
1172 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1173 -- understand /cygdrive paths.)
1175 | "/cygdrive/" `isPrefixOf` path =
1176 case drop (length "/cygdrive/") path of
1177 drive:xs@('/':_) -> drive:':':xs
1181 -- strip the trailing backslash (awful, but we only do this once).
1182 removeTrailingSlash path =
1189 -----------------------------------------------------------------------------
1190 -- Via-C compilation stuff
1192 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1193 [String]) -- for registerised HC compilations
1194 machdepCCOpts dflags
1195 #if alpha_TARGET_ARCH
1197 #ifdef HAVE_THREADED_RTS_SUPPORT
1201 -- For now, to suppress the gcc warning "call-clobbered
1202 -- register used for global register variable", we simply
1203 -- disable all warnings altogether using the -w flag. Oh well.
1205 #elif hppa_TARGET_ARCH
1206 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1207 -- (very nice, but too bad the HP /usr/include files don't agree.)
1208 = ( ["-D_HPUX_SOURCE"], [] )
1210 #elif m68k_TARGET_ARCH
1211 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1212 -- popping of args to routines to be explicit; if we let things
1213 -- be deferred 'til after an STGJUMP, imminent death is certain!
1215 -- -fomit-frame-pointer : *don't*
1216 -- It's better to have a6 completely tied up being a frame pointer
1217 -- rather than let GCC pick random things to do with it.
1218 -- (If we want to steal a6, then we would try to do things
1219 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1220 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1222 #elif i386_TARGET_ARCH
1223 -- -fno-defer-pop : basically the same game as for m68k
1225 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1226 -- the fp (%ebp) for our register maps.
1227 = let n_regs = stolen_x86_regs dflags
1230 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1231 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1234 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1235 -- Some gccs are configured with
1236 -- -momit-leaf-frame-pointer on by default, and it
1237 -- apparently takes precedence over
1238 -- -fomit-frame-pointer, so we disable it first here.
1239 "-mno-omit-leaf-frame-pointer",
1241 "-fomit-frame-pointer",
1242 -- we want -fno-builtin, because when gcc inlines
1243 -- built-in functions like memcpy() it tends to
1244 -- run out of registers, requiring -monly-n-regs
1246 "-DSTOLEN_X86_REGS="++show n_regs ]
1249 #elif ia64_TARGET_ARCH
1250 = ( [], ["-fomit-frame-pointer", "-G0"] )
1252 #elif x86_64_TARGET_ARCH
1253 = ( [], ["-fomit-frame-pointer",
1254 "-fno-asynchronous-unwind-tables",
1255 -- the unwind tables are unnecessary for HC code,
1256 -- and get in the way of -split-objs. Another option
1257 -- would be to throw them away in the mangler, but this
1259 "-fno-unit-at-a-time"
1260 -- unit-at-a-time doesn't do us any good, and screws
1261 -- up -split-objs by moving the split markers around.
1262 -- It's only turned on with -O2, but put it here just
1263 -- in case someone uses -optc-O2.
1266 #elif mips_TARGET_ARCH
1267 = ( ["-static"], [] )
1269 #elif sparc_TARGET_ARCH
1271 -- For now, to suppress the gcc warning "call-clobbered
1272 -- register used for global register variable", we simply
1273 -- disable all warnings altogether using the -w flag. Oh well.
1275 #elif powerpc_apple_darwin_TARGET
1277 -- Disable Apple's precompiling preprocessor. It's a great thing
1278 -- for "normal" programs, but it doesn't support register variable
1280 = ( [], ["-no-cpp-precomp"] )
1285 picCCOpts :: DynFlags -> [String]
1287 #if darwin_TARGET_OS
1288 -- Apple prefers to do things the other way round.
1289 -- PIC is on by default.
1290 -- -mdynamic-no-pic:
1291 -- Turn off PIC code generation.
1293 -- Don't generate "common" symbols - these are unwanted
1294 -- in dynamic libraries.
1299 = ["-mdynamic-no-pic"]
1300 #elif mingw32_TARGET_OS
1301 -- no -fPIC for Windows
1310 -- -----------------------------------------------------------------------------
1315 #if defined(i386_TARGET_ARCH) \
1316 || defined(x86_64_TARGET_ARCH) \
1317 || defined(alpha_TARGET_ARCH) \
1318 || defined(hppa_TARGET_ARCH) \
1319 || defined(m68k_TARGET_ARCH) \
1320 || defined(mips_TARGET_ARCH) \
1321 || defined(powerpc_TARGET_ARCH) \
1322 || defined(rs6000_TARGET_ARCH) \
1323 || defined(sparc_TARGET_ARCH)