1 {-# OPTIONS -fno-warn-missing-fields #-}
2 -----------------------------------------------------------------------------
6 -- Most flags are dynamic flags, which means they can change from
7 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
8 -- multi-session GHC each session can be using different dynamic
9 -- flags. Dynamic flags can also be set at the prompt in GHCi.
11 -- (c) The University of Glasgow 2005
13 -----------------------------------------------------------------------------
20 GhcMode(..), isOneShot,
21 GhcLink(..), isNoLink,
25 -- Configuration of the core-to-core and stg-to-stg phases
29 SimplifierMode(..), FloatOutSwitches(..),
30 getCoreToDo, getStgToDo,
32 -- Manipulating DynFlags
33 defaultDynFlags, -- DynFlags
34 initDynFlags, -- DynFlags -> IO DynFlags
36 dopt, -- DynFlag -> DynFlags -> Bool
37 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
38 getOpts, -- (DynFlags -> [a]) -> IO [a]
49 machdepCCOpts, picCCOpts
52 #include "HsVersions.h"
54 import Module ( Module, mkModuleName, mkModule )
56 import PrelNames ( mAIN )
57 #ifdef i386_TARGET_ARCH
58 import StaticFlags ( opt_Static )
60 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
62 import {-# SOURCE #-} Packages (PackageState)
63 import DriverPhases ( Phase(..), phaseInputExt )
66 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
67 import Panic ( panic, GhcException(..) )
68 import UniqFM ( UniqFM )
69 import Util ( notNull, splitLongestPrefix, normalisePath )
70 import Maybes ( fromJust, orElse )
71 import SrcLoc ( SrcSpan )
73 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
75 import Data.IORef ( readIORef )
76 import Control.Exception ( throwDyn )
77 import Control.Monad ( when )
78 #ifdef mingw32_TARGET_OS
79 import Data.List ( isPrefixOf )
84 import Data.Char ( isDigit, isUpper )
85 import System.IO ( hPutStrLn, stderr )
87 import Breakpoints ( BkptHandler )
88 import Module ( ModuleName )
90 -- -----------------------------------------------------------------------------
103 | Opt_D_dump_inlinings
104 | Opt_D_dump_occur_anal
108 | Opt_D_dump_simpl_iterations
117 | Opt_D_dump_worker_wrapper
118 | Opt_D_dump_rn_trace
119 | Opt_D_dump_rn_stats
121 | Opt_D_dump_simpl_stats
122 | Opt_D_dump_tc_trace
123 | Opt_D_dump_if_trace
129 | Opt_D_verbose_core2core
130 | Opt_D_verbose_stg2stg
132 | Opt_D_dump_hi_diffs
133 | Opt_D_dump_minimal_imports
134 | Opt_D_faststring_stats
139 | Opt_WarnIsError -- -Werror; makes warnings fatal
140 | Opt_WarnDuplicateExports
142 | Opt_WarnIncompletePatterns
143 | Opt_WarnIncompletePatternsRecUpd
144 | Opt_WarnMissingFields
145 | Opt_WarnMissingMethods
146 | Opt_WarnMissingSigs
147 | Opt_WarnNameShadowing
148 | Opt_WarnOverlappingPatterns
149 | Opt_WarnSimplePatterns
150 | Opt_WarnTypeDefaults
151 | Opt_WarnUnusedBinds
152 | Opt_WarnUnusedImports
153 | Opt_WarnUnusedMatches
154 | Opt_WarnDeprecations
155 | Opt_WarnDodgyImports
159 | Opt_AllowOverlappingInstances
160 | Opt_AllowUndecidableInstances
161 | Opt_AllowIncoherentInstances
162 | Opt_MonomorphismRestriction
164 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
167 | Opt_PArr -- Syntactic support for parallel arrays
168 | Opt_Arrows -- Arrow-notation syntax
172 | Opt_ImplicitPrelude
173 | Opt_ScopedTypeVariables
181 | Opt_IgnoreInterfacePragmas
182 | Opt_OmitInterfacePragmas
183 | Opt_DoLambdaEtaExpansion
185 | Opt_IgnoreBreakpoints
188 | Opt_UnboxStrictFields
197 | Opt_ExcessPrecision
198 | Opt_ReadUserPackageConf
202 | Opt_HideAllPackages
203 | Opt_PrintBindResult
215 data DynFlags = DynFlags {
218 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
219 stgToDo :: Maybe [StgToDo], -- similarly
220 hscTarget :: HscTarget,
221 hscOutName :: String, -- name of the output file
222 extCoreName :: String, -- name of the .core output file
223 verbosity :: Int, -- verbosity level
224 optLevel :: Int, -- optimisation level
225 maxSimplIterations :: Int, -- max simplifier iterations
226 ruleCheck :: Maybe String,
227 stolen_x86_regs :: Int,
228 cmdlineHcIncludes :: [String], -- -#includes
229 importPaths :: [FilePath],
231 mainFunIs :: Maybe String,
232 ctxtStkDepth :: Int, -- Typechecker context stack depth
234 thisPackage :: PackageId,
237 wayNames :: [WayName], -- way flags from the cmd line
238 buildTag :: String, -- the global "way" (eg. "p" for prof)
239 rtsBuildTag :: String, -- the RTS "way"
242 objectDir :: Maybe String,
243 hiDir :: Maybe String,
244 stubDir :: Maybe String,
250 outputFile :: Maybe String,
251 outputHi :: Maybe String,
253 includePaths :: [String],
254 libraryPaths :: [String],
255 frameworkPaths :: [String], -- used on darwin only
256 cmdlineFrameworks :: [String], -- ditto
257 tmpDir :: String, -- no trailing '/'
259 ghcUsagePath :: FilePath, -- Filled in by SysTools
260 ghciUsagePath :: FilePath, -- ditto
262 hpcDir :: String, -- ^ path to store the .mix files
264 -- options for particular phases
275 -- commands for particular phases
277 pgm_P :: (String,[Option]),
279 pgm_c :: (String,[Option]),
280 pgm_m :: (String,[Option]),
281 pgm_s :: (String,[Option]),
282 pgm_a :: (String,[Option]),
283 pgm_l :: (String,[Option]),
284 pgm_dll :: (String,[Option]),
286 pgm_sysman :: String,
289 extraPkgConfs :: [FilePath],
290 topDir :: FilePath, -- filled in by SysTools
291 systemPackageConfig :: FilePath, -- ditto
292 -- The -package-conf flags given on the command line, in the order
295 packageFlags :: [PackageFlag],
296 -- The -package and -hide-package flags from the command-line
299 -- NB. do not modify this field, it is calculated by
300 -- Packages.initPackages and Packages.updatePackages.
301 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
302 pkgState :: PackageState,
308 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
310 -- breakpoint handling
311 ,bkptHandler :: Maybe (BkptHandler Module)
323 = BatchCompile -- | @ghc --make Main@
324 | Interactive -- | @ghc --interactive@
325 | OneShot -- | @ghc -c Foo.hs@
326 | JustTypecheck -- | Development environemnts, refactorer, etc.
330 isOneShot :: GhcMode -> Bool
331 isOneShot OneShot = True
332 isOneShot _other = False
334 data GhcLink -- What to do in the link step, if there is one
335 = -- Only relevant for modes
336 -- DoMake and StopBefore StopLn
337 NoLink -- Don't link at all
338 | StaticLink -- Ordinary linker [the default]
339 | MkDLL -- Make a DLL
341 isNoLink :: GhcLink -> Bool
342 isNoLink NoLink = True
343 isNoLink other = False
346 = ExposePackage String
348 | IgnorePackage String
352 | cGhcWithNativeCodeGen == "YES" = HscAsm
355 initDynFlags dflags = do
356 -- someday these will be dynamic flags
357 ways <- readIORef v_Ways
358 build_tag <- readIORef v_Build_tag
359 rts_build_tag <- readIORef v_RTS_Build_tag
362 buildTag = build_tag,
363 rtsBuildTag = rts_build_tag
369 ghcLink = StaticLink,
372 hscTarget = defaultHscTarget,
377 maxSimplIterations = 4,
380 cmdlineHcIncludes = [],
384 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
386 thisPackage = mainPackageId,
392 objectSuf = phaseInputExt StopLn,
393 hcSuf = phaseInputExt HCc,
396 outputFile = Nothing,
401 cmdlineFrameworks = [],
402 tmpDir = cDEFAULT_TMPDIR,
418 pkgDatabase = Nothing,
419 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
421 bkptHandler = Nothing,
423 Opt_ReadUserPackageConf,
425 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
426 -- behaviour the default, to see if anyone notices
430 Opt_MonomorphismRestriction,
432 -- strictness is on by default, but this only
434 Opt_CSE, -- similarly for CSE.
435 Opt_FullLaziness, -- ...and for full laziness
437 Opt_DoLambdaEtaExpansion,
438 -- This one is important for a tiresome reason:
439 -- we want to make sure that the bindings for data
440 -- constructors are eta-expanded. This is probably
441 -- a good thing anyway, but it seems fragile.
445 -- and the default no-optimisation options:
446 Opt_IgnoreInterfacePragmas,
447 Opt_OmitInterfacePragmas,
451 ] ++ standardWarnings,
453 log_action = \severity srcSpan style msg ->
455 SevInfo -> hPutStrLn stderr (show (msg style))
456 SevFatal -> hPutStrLn stderr (show (msg style))
457 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
463 0 | print errors & warnings only
464 1 | minimal verbosity: print "compiling M ... done." for each module.
465 2 | equivalent to -dshow-passes
466 3 | equivalent to existing "ghc -v"
467 4 | "ghc -v -ddump-most"
468 5 | "ghc -v -ddump-all"
471 dopt :: DynFlag -> DynFlags -> Bool
472 dopt f dflags = f `elem` (flags dflags)
474 dopt_set :: DynFlags -> DynFlag -> DynFlags
475 dopt_set dfs f = dfs{ flags = f : flags dfs }
477 dopt_unset :: DynFlags -> DynFlag -> DynFlags
478 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
480 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
481 getOpts dflags opts = reverse (opts dflags)
482 -- We add to the options from the front, so we need to reverse the list
484 getVerbFlag :: DynFlags -> String
486 | verbosity dflags >= 3 = "-v"
489 setObjectDir f d = d{ objectDir = f}
490 setHiDir f d = d{ hiDir = f}
491 setStubDir f d = d{ stubDir = f}
493 setObjectSuf f d = d{ objectSuf = f}
494 setHiSuf f d = d{ hiSuf = f}
495 setHcSuf f d = d{ hcSuf = f}
497 setOutputFile f d = d{ outputFile = f}
498 setOutputHi f d = d{ outputHi = f}
500 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
501 -- Config.hs should really use Option.
502 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
504 setPgmL f d = d{ pgm_L = f}
505 setPgmF f d = d{ pgm_F = f}
506 setPgmc f d = d{ pgm_c = (f,[])}
507 setPgmm f d = d{ pgm_m = (f,[])}
508 setPgms f d = d{ pgm_s = (f,[])}
509 setPgma f d = d{ pgm_a = (f,[])}
510 setPgml f d = d{ pgm_l = (f,[])}
511 setPgmdll f d = d{ pgm_dll = (f,[])}
513 addOptL f d = d{ opt_L = f : opt_L d}
514 addOptP f d = d{ opt_P = f : opt_P d}
515 addOptF f d = d{ opt_F = f : opt_F d}
516 addOptc f d = d{ opt_c = f : opt_c d}
517 addOptm f d = d{ opt_m = f : opt_m d}
518 addOpta f d = d{ opt_a = f : opt_a d}
519 addOptl f d = d{ opt_l = f : opt_l d}
520 addOptdll f d = d{ opt_dll = f : opt_dll d}
521 addOptdep f d = d{ opt_dep = f : opt_dep d}
523 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
525 -- -----------------------------------------------------------------------------
526 -- Command-line options
528 -- When invoking external tools as part of the compilation pipeline, we
529 -- pass these a sequence of options on the command-line. Rather than
530 -- just using a list of Strings, we use a type that allows us to distinguish
531 -- between filepaths and 'other stuff'. [The reason being, of course, that
532 -- this type gives us a handle on transforming filenames, and filenames only,
533 -- to whatever format they're expected to be on a particular platform.]
536 = FileOption -- an entry that _contains_ filename(s) / filepaths.
537 String -- a non-filepath prefix that shouldn't be
538 -- transformed (e.g., "/out=")
539 String -- the filepath/filename portion
542 -----------------------------------------------------------------------------
543 -- Setting the optimisation level
545 updOptLevel :: Int -> DynFlags -> DynFlags
546 -- Set dynflags appropriate to the optimisation level
548 = dfs2{ optLevel = n }
550 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
551 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
554 | n == 0 = opt_0_dopts
555 | otherwise = opt_1_dopts
558 | n == 0 = opt_1_dopts
559 | otherwise = opt_0_dopts
562 Opt_IgnoreInterfacePragmas,
563 Opt_OmitInterfacePragmas
572 -- -----------------------------------------------------------------------------
573 -- Standard sets of warning options
576 = [ Opt_WarnDeprecations,
577 Opt_WarnOverlappingPatterns,
578 Opt_WarnMissingFields,
579 Opt_WarnMissingMethods,
580 Opt_WarnDuplicateExports
584 = standardWarnings ++
585 [ Opt_WarnUnusedBinds,
586 Opt_WarnUnusedMatches,
587 Opt_WarnUnusedImports,
588 Opt_WarnIncompletePatterns,
594 [ Opt_WarnTypeDefaults,
595 Opt_WarnNameShadowing,
601 -- -----------------------------------------------------------------------------
602 -- CoreToDo: abstraction of core-to-core passes to run.
604 data CoreToDo -- These are diff core-to-core passes,
605 -- which may be invoked in any order,
606 -- as many times as you like.
608 = CoreDoSimplify -- The core-to-core simplifier.
611 -- Each run of the simplifier can take a different
612 -- set of simplifier-specific flags.
614 | CoreDoFloatOutwards FloatOutSwitches
619 | CoreDoWorkerWrapper
622 | CoreDoOldStrictness
625 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
626 -- matching this string
628 | CoreDoNothing -- useful when building up lists of these things
630 data SimplifierMode -- See comments in SimplMonad
634 data SimplifierSwitch
635 = MaxSimplifierIterations Int
638 data FloatOutSwitches
639 = FloatOutSw Bool -- True <=> float lambdas to top level
640 Bool -- True <=> float constants to top level,
641 -- even if they do not escape a lambda
644 -- The core-to-core pass ordering is derived from the DynFlags:
646 getCoreToDo :: DynFlags -> [CoreToDo]
648 | Just todo <- coreToDo dflags = todo -- set explicitly by user
649 | otherwise = core_todo
651 opt_level = optLevel dflags
652 max_iter = maxSimplIterations dflags
653 strictness = dopt Opt_Strictness dflags
654 full_laziness = dopt Opt_FullLaziness dflags
655 cse = dopt Opt_CSE dflags
656 rule_check = ruleCheck dflags
659 if opt_level == 0 then
661 CoreDoSimplify (SimplPhase 0) [
662 MaxSimplifierIterations max_iter
665 else {- opt_level >= 1 -} [
667 -- initial simplify: mk specialiser happy: minimum effort please
668 CoreDoSimplify SimplGently [
670 -- Don't inline anything till full laziness has bitten
671 -- In particular, inlining wrappers inhibits floating
672 -- e.g. ...(case f x of ...)...
673 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
674 -- ==> ...(case x of I# x# -> case fw x# of ...)...
675 -- and now the redex (f x) isn't floatable any more
676 -- Similarly, don't apply any rules until after full
677 -- laziness. Notably, list fusion can prevent floating.
679 NoCaseOfCase, -- Don't do case-of-case transformations.
680 -- This makes full laziness work better
681 MaxSimplifierIterations max_iter
684 -- Specialisation is best done before full laziness
685 -- so that overloaded functions have all their dictionary lambdas manifest
688 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
693 CoreDoSimplify (SimplPhase 2) [
694 -- Want to run with inline phase 2 after the specialiser to give
695 -- maximum chance for fusion to work before we inline build/augment
696 -- in phase 1. This made a difference in 'ansi' where an
697 -- overloaded function wasn't inlined till too late.
698 MaxSimplifierIterations max_iter
700 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
702 CoreDoSimplify (SimplPhase 1) [
703 -- Need inline-phase2 here so that build/augment get
704 -- inlined. I found that spectral/hartel/genfft lost some useful
705 -- strictness in the function sumcode' if augment is not inlined
706 -- before strictness analysis runs
707 MaxSimplifierIterations max_iter
709 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
711 CoreDoSimplify (SimplPhase 0) [
712 -- Phase 0: allow all Ids to be inlined now
713 -- This gets foldr inlined before strictness analysis
715 MaxSimplifierIterations 3
716 -- At least 3 iterations because otherwise we land up with
717 -- huge dead expressions because of an infelicity in the
719 -- let k = BIG in foldr k z xs
720 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
721 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
725 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
727 #ifdef OLD_STRICTNESS
730 if strictness then CoreDoStrictness else CoreDoNothing,
734 CoreDoSimplify (SimplPhase 0) [
735 MaxSimplifierIterations max_iter
738 if full_laziness then
739 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
740 True) -- Float constants
742 -- nofib/spectral/hartel/wang doubles in speed if you
743 -- do full laziness late in the day. It only happens
744 -- after fusion and other stuff, so the early pass doesn't
745 -- catch it. For the record, the redex is
746 -- f_el22 (f_el21 r_midblock)
749 -- We want CSE to follow the final full-laziness pass, because it may
750 -- succeed in commoning up things floated out by full laziness.
751 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
753 if cse then CoreCSE else CoreDoNothing,
757 -- Case-liberation for -O2. This should be after
758 -- strictness analysis and the simplification which follows it.
760 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
765 (if opt_level >= 2 then
767 CoreDoSimplify (SimplPhase 0) [
768 MaxSimplifierIterations max_iter
769 ], -- Run the simplifier after LiberateCase to vastly
770 -- reduce the possiblility of shadowing
771 -- Reason: see Note [Shadowing] in SpecConstr.lhs
779 -- Final clean-up simplification:
780 [ CoreDoSimplify (SimplPhase 0) [
781 MaxSimplifierIterations max_iter
785 -- -----------------------------------------------------------------------------
786 -- StgToDo: abstraction of stg-to-stg passes to run.
789 = StgDoMassageForProfiling -- should be (next to) last
790 -- There's also setStgVarInfo, but its absolute "lastness"
791 -- is so critical that it is hardwired in (no flag).
794 getStgToDo :: DynFlags -> [StgToDo]
796 | Just todo <- stgToDo dflags = todo -- set explicitly by user
799 stg_stats = dopt Opt_StgStats dflags
801 todo1 = if stg_stats then [D_stg_stats] else []
803 todo2 | WayProf `elem` wayNames dflags
804 = StgDoMassageForProfiling : todo1
808 -- -----------------------------------------------------------------------------
812 allFlags = map ('-':) $
813 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
814 map ("fno-"++) flags ++
816 where ok (PrefixPred _ _) = False
818 flags = map fst fFlags
820 dynamic_flags :: [(String, OptKind DynP)]
822 ( "n" , NoArg (setDynFlag Opt_DryRun) )
823 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
824 , ( "F" , NoArg (setDynFlag Opt_Pp))
825 , ( "#include" , HasArg (addCmdlineHCInclude) )
826 , ( "v" , OptIntSuffix setVerbosity )
827 ------- Specific phases --------------------------------------------
828 , ( "pgmL" , HasArg (upd . setPgmL) )
829 , ( "pgmP" , HasArg (upd . setPgmP) )
830 , ( "pgmF" , HasArg (upd . setPgmF) )
831 , ( "pgmc" , HasArg (upd . setPgmc) )
832 , ( "pgmm" , HasArg (upd . setPgmm) )
833 , ( "pgms" , HasArg (upd . setPgms) )
834 , ( "pgma" , HasArg (upd . setPgma) )
835 , ( "pgml" , HasArg (upd . setPgml) )
836 , ( "pgmdll" , HasArg (upd . setPgmdll) )
838 , ( "optL" , HasArg (upd . addOptL) )
839 , ( "optP" , HasArg (upd . addOptP) )
840 , ( "optF" , HasArg (upd . addOptF) )
841 , ( "optc" , HasArg (upd . addOptc) )
842 , ( "optm" , HasArg (upd . addOptm) )
843 , ( "opta" , HasArg (upd . addOpta) )
844 , ( "optl" , HasArg (upd . addOptl) )
845 , ( "optdll" , HasArg (upd . addOptdll) )
846 , ( "optdep" , HasArg (upd . addOptdep) )
848 , ( "split-objs" , NoArg (if can_split
849 then setDynFlag Opt_SplitObjs
852 -------- Linking ----------------------------------------------------
853 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
854 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
855 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
857 ------- Libraries ---------------------------------------------------
858 , ( "L" , Prefix addLibraryPath )
859 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
862 ------- Frameworks --------------------------------------------------
863 -- -framework-path should really be -F ...
864 , ( "framework-path" , HasArg addFrameworkPath )
865 , ( "framework" , HasArg (upd . addCmdlineFramework) )
867 ------- Output Redirection ------------------------------------------
868 , ( "odir" , HasArg (upd . setObjectDir . Just))
869 , ( "o" , SepArg (upd . setOutputFile . Just))
870 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
871 , ( "osuf" , HasArg (upd . setObjectSuf))
872 , ( "hcsuf" , HasArg (upd . setHcSuf))
873 , ( "hisuf" , HasArg (upd . setHiSuf))
874 , ( "hidir" , HasArg (upd . setHiDir . Just))
875 , ( "tmpdir" , HasArg (upd . setTmpDir))
876 , ( "stubdir" , HasArg (upd . setStubDir . Just))
878 ------- Keeping temporary files -------------------------------------
879 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
880 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
881 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
882 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
884 ------- Miscellaneous ----------------------------------------------
885 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
886 , ( "main-is" , SepArg setMainIs )
887 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
888 , ( "hpcdir" , SepArg setOptHpcDir )
890 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
891 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
892 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
894 ------- Packages ----------------------------------------------------
895 , ( "package-conf" , HasArg extraPkgConf_ )
896 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
897 , ( "package-name" , HasArg (upd . setPackageName) )
898 , ( "package" , HasArg exposePackage )
899 , ( "hide-package" , HasArg hidePackage )
900 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
901 , ( "ignore-package" , HasArg ignorePackage )
902 , ( "syslib" , HasArg exposePackage ) -- for compatibility
904 ------ HsCpp opts ---------------------------------------------------
905 , ( "D", AnySuffix (upd . addOptP) )
906 , ( "U", AnySuffix (upd . addOptP) )
908 ------- Include/Import Paths ----------------------------------------
909 , ( "I" , Prefix addIncludePath)
910 , ( "i" , OptPrefix addImportPath )
912 ------ Debugging ----------------------------------------------------
913 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
915 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
916 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
917 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
918 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
919 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
920 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
921 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
922 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
923 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
924 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
925 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
926 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
927 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
928 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
929 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
930 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
931 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
932 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
933 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
934 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
935 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
936 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
937 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
938 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
939 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
940 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
941 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
942 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
943 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
944 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
945 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
946 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
947 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
948 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
949 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
950 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
951 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
952 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
954 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
955 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
956 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
957 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
958 setVerbosity (Just 2)) )
959 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
961 ------ Machine dependant (-m<blah>) stuff ---------------------------
963 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
964 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
965 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
967 ------ Warning opts -------------------------------------------------
968 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
969 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
970 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
971 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
972 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
974 ------ Optimisation flags ------------------------------------------
975 , ( "O" , NoArg (upd (setOptLevel 1)))
976 , ( "Onot" , NoArg (upd (setOptLevel 0)))
977 , ( "O" , PrefixPred (all isDigit)
978 (\f -> upd (setOptLevel (read f))))
980 , ( "fmax-simplifier-iterations",
981 PrefixPred (all isDigit)
983 dfs{ maxSimplIterations = read n })) )
986 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
988 ------ Compiler flags -----------------------------------------------
990 , ( "fno-code", NoArg (setTarget HscNothing))
991 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
992 , ( "fvia-c", NoArg (setTarget HscC) )
993 , ( "fvia-C", NoArg (setTarget HscC) )
995 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
996 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
998 , ( "fcontext-stack" , OptIntSuffix $ \mb_n -> upd $ \dfs ->
999 dfs{ ctxtStkDepth = mb_n `orElse` 3 })
1001 -- the rest of the -f* and -fno-* flags
1002 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
1003 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
1006 -- these -f<blah> flags can all be reversed with -fno-<blah>
1009 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1010 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1011 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1012 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1013 ( "warn-missing-fields", Opt_WarnMissingFields ),
1014 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1015 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1016 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1017 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1018 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1019 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1020 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1021 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1022 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1023 ( "warn-deprecations", Opt_WarnDeprecations ),
1024 ( "warn-orphans", Opt_WarnOrphans ),
1025 ( "fi", Opt_FFI ), -- support `-ffi'...
1026 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
1027 ( "arrows", Opt_Arrows ), -- arrow syntax
1028 ( "parr", Opt_PArr ),
1030 ( "implicit-prelude", Opt_ImplicitPrelude ),
1031 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1032 ( "bang-patterns", Opt_BangPatterns ),
1033 ( "indexed-types", Opt_IndexedTypes ),
1034 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1035 ( "mono-pat-binds", Opt_MonoPatBinds ),
1036 ( "extended-default-rules", Opt_ExtendedDefaultRules ),
1037 ( "implicit-params", Opt_ImplicitParams ),
1038 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
1039 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
1040 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
1041 ( "generics", Opt_Generics ),
1042 ( "strictness", Opt_Strictness ),
1043 ( "full-laziness", Opt_FullLaziness ),
1045 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1046 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1047 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1048 ( "ignore-asserts", Opt_IgnoreAsserts ),
1049 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1050 ( "do-eta-reduction", Opt_DoEtaReduction ),
1051 ( "case-merge", Opt_CaseMerge ),
1052 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1053 ( "dicts-cheap", Opt_DictsCheap ),
1054 ( "excess-precision", Opt_ExcessPrecision ),
1055 ( "asm-mangling", Opt_DoAsmMangling ),
1056 ( "print-bind-result", Opt_PrintBindResult ),
1057 ( "force-recomp", Opt_ForceRecomp )
1061 glasgowExtsFlags = [
1065 Opt_ScopedTypeVariables,
1068 isFFlag f = f `elem` (map fst fFlags)
1069 getFFlag f = fromJust (lookup f fFlags)
1071 -- -----------------------------------------------------------------------------
1072 -- Parsing the dynamic flags.
1074 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1075 parseDynamicFlags dflags args = do
1076 let ((leftover,errs),dflags')
1077 = runCmdLine (processArgs dynamic_flags args) dflags
1078 when (not (null errs)) $ do
1079 throwDyn (UsageError (unlines errs))
1080 return (dflags', leftover)
1083 type DynP = CmdLineP DynFlags
1085 upd :: (DynFlags -> DynFlags) -> DynP ()
1087 dfs <- getCmdLineState
1088 putCmdLineState $! (f dfs)
1090 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1091 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1092 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1094 setDumpFlag :: DynFlag -> OptKind DynP
1095 setDumpFlag dump_flag
1096 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1097 -- Whenver we -ddump, switch off the recompilation checker,
1098 -- else you don't see the dump!
1100 setVerbosity :: Maybe Int -> DynP ()
1101 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1103 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1105 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1108 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1110 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1112 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1115 | Nothing <- unpackPackageId pid
1116 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1118 = \s -> s{ thisPackage = pid }
1120 pid = stringToPackageId p
1122 -- we can only switch between HscC, and HscAsmm with dynamic flags
1123 -- (-fvia-C, -fasm, -filx respectively).
1124 setTarget l = upd (\dfs -> case hscTarget dfs of
1125 HscC -> dfs{ hscTarget = l }
1126 HscAsm -> dfs{ hscTarget = l }
1129 setOptLevel :: Int -> DynFlags -> DynFlags
1130 setOptLevel n dflags
1131 | hscTarget dflags == HscInterpreted && n > 0
1133 -- not in IO any more, oh well:
1134 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1136 = updOptLevel n dflags
1139 setMainIs :: String -> DynP ()
1141 | not (null main_fn) -- The arg looked like "Foo.baz"
1142 = upd $ \d -> d{ mainFunIs = Just main_fn,
1143 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1145 | isUpper (head main_mod) -- The arg looked like "Foo"
1146 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1148 | otherwise -- The arg looked like "baz"
1149 = upd $ \d -> d{ mainFunIs = Just main_mod }
1151 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1153 -----------------------------------------------------------------------------
1154 -- Paths & Libraries
1156 -- -i on its own deletes the import paths
1157 addImportPath "" = upd (\s -> s{importPaths = []})
1158 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1162 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1165 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1167 addFrameworkPath p =
1168 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1170 split_marker = ':' -- not configurable (ToDo)
1172 splitPathList :: String -> [String]
1173 splitPathList s = filter notNull (splitUp s)
1174 -- empty paths are ignored: there might be a trailing
1175 -- ':' in the initial list, for example. Empty paths can
1176 -- cause confusion when they are translated into -I options
1177 -- for passing to gcc.
1179 #ifndef mingw32_TARGET_OS
1180 splitUp xs = split split_marker xs
1182 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1184 -- That is, if "foo:bar:baz" is used, this interpreted as
1185 -- consisting of three entries, 'foo', 'bar', 'baz'.
1186 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1187 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1189 -- Notice that no attempt is made to fully replace the 'standard'
1190 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1191 -- that this will cause too much breakage for users & ':' will
1192 -- work fine even with DOS paths, if you're not insisting on being silly.
1195 splitUp (x:':':div:xs) | div `elem` dir_markers
1196 = ((x:':':div:p): splitUp rs)
1198 (p,rs) = findNextPath xs
1199 -- we used to check for existence of the path here, but that
1200 -- required the IO monad to be threaded through the command-line
1201 -- parser which is quite inconvenient. The
1202 splitUp xs = cons p (splitUp rs)
1204 (p,rs) = findNextPath xs
1209 -- will be called either when we've consumed nought or the
1210 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1211 -- finding the next split marker.
1213 case break (`elem` split_markers) xs of
1214 (p, d:ds) -> (p, ds)
1217 split_markers :: [Char]
1218 split_markers = [':', ';']
1220 dir_markers :: [Char]
1221 dir_markers = ['/', '\\']
1224 -- -----------------------------------------------------------------------------
1225 -- tmpDir, where we store temporary files.
1227 setTmpDir :: FilePath -> DynFlags -> DynFlags
1228 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1230 #if !defined(mingw32_HOST_OS)
1231 canonicalise p = normalisePath p
1233 -- Canonicalisation of temp path under win32 is a bit more
1234 -- involved: (a) strip trailing slash,
1235 -- (b) normalise slashes
1236 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1238 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1240 -- if we're operating under cygwin, and TMP/TEMP is of
1241 -- the form "/cygdrive/drive/path", translate this to
1242 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1243 -- understand /cygdrive paths.)
1245 | "/cygdrive/" `isPrefixOf` path =
1246 case drop (length "/cygdrive/") path of
1247 drive:xs@('/':_) -> drive:':':xs
1251 -- strip the trailing backslash (awful, but we only do this once).
1252 removeTrailingSlash path =
1259 -----------------------------------------------------------------------------
1262 setOptHpcDir :: String -> DynP ()
1263 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1265 -----------------------------------------------------------------------------
1266 -- Via-C compilation stuff
1268 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1269 [String]) -- for registerised HC compilations
1270 machdepCCOpts dflags
1271 #if alpha_TARGET_ARCH
1273 #ifdef HAVE_THREADED_RTS_SUPPORT
1277 -- For now, to suppress the gcc warning "call-clobbered
1278 -- register used for global register variable", we simply
1279 -- disable all warnings altogether using the -w flag. Oh well.
1281 #elif hppa_TARGET_ARCH
1282 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1283 -- (very nice, but too bad the HP /usr/include files don't agree.)
1284 = ( ["-D_HPUX_SOURCE"], [] )
1286 #elif m68k_TARGET_ARCH
1287 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1288 -- popping of args to routines to be explicit; if we let things
1289 -- be deferred 'til after an STGJUMP, imminent death is certain!
1291 -- -fomit-frame-pointer : *don't*
1292 -- It's better to have a6 completely tied up being a frame pointer
1293 -- rather than let GCC pick random things to do with it.
1294 -- (If we want to steal a6, then we would try to do things
1295 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1296 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1298 #elif i386_TARGET_ARCH
1299 -- -fno-defer-pop : basically the same game as for m68k
1301 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1302 -- the fp (%ebp) for our register maps.
1303 = let n_regs = stolen_x86_regs dflags
1306 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1307 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1310 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1311 -- Some gccs are configured with
1312 -- -momit-leaf-frame-pointer on by default, and it
1313 -- apparently takes precedence over
1314 -- -fomit-frame-pointer, so we disable it first here.
1315 "-mno-omit-leaf-frame-pointer",
1317 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1318 "-fno-unit-at-a-time",
1319 -- unit-at-a-time doesn't do us any good, and screws
1320 -- up -split-objs by moving the split markers around.
1321 -- It's only turned on with -O2, but put it here just
1322 -- in case someone uses -optc-O2.
1324 "-fomit-frame-pointer",
1325 -- we want -fno-builtin, because when gcc inlines
1326 -- built-in functions like memcpy() it tends to
1327 -- run out of registers, requiring -monly-n-regs
1329 "-DSTOLEN_X86_REGS="++show n_regs ]
1332 #elif ia64_TARGET_ARCH
1333 = ( [], ["-fomit-frame-pointer", "-G0"] )
1335 #elif x86_64_TARGET_ARCH
1336 = ( [], ["-fomit-frame-pointer",
1337 "-fno-asynchronous-unwind-tables",
1338 -- the unwind tables are unnecessary for HC code,
1339 -- and get in the way of -split-objs. Another option
1340 -- would be to throw them away in the mangler, but this
1342 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1343 "-fno-unit-at-a-time",
1344 -- unit-at-a-time doesn't do us any good, and screws
1345 -- up -split-objs by moving the split markers around.
1346 -- It's only turned on with -O2, but put it here just
1347 -- in case someone uses -optc-O2.
1350 -- calling builtins like strlen() using the FFI can
1351 -- cause gcc to run out of regs, so use the external
1355 #elif sparc_TARGET_ARCH
1357 -- For now, to suppress the gcc warning "call-clobbered
1358 -- register used for global register variable", we simply
1359 -- disable all warnings altogether using the -w flag. Oh well.
1361 #elif powerpc_apple_darwin_TARGET
1363 -- Disable Apple's precompiling preprocessor. It's a great thing
1364 -- for "normal" programs, but it doesn't support register variable
1366 = ( [], ["-no-cpp-precomp"] )
1371 picCCOpts :: DynFlags -> [String]
1373 #if darwin_TARGET_OS
1374 -- Apple prefers to do things the other way round.
1375 -- PIC is on by default.
1376 -- -mdynamic-no-pic:
1377 -- Turn off PIC code generation.
1379 -- Don't generate "common" symbols - these are unwanted
1380 -- in dynamic libraries.
1385 = ["-mdynamic-no-pic"]
1386 #elif mingw32_TARGET_OS
1387 -- no -fPIC for Windows
1396 -- -----------------------------------------------------------------------------
1401 #if defined(i386_TARGET_ARCH) \
1402 || defined(x86_64_TARGET_ARCH) \
1403 || defined(alpha_TARGET_ARCH) \
1404 || defined(hppa_TARGET_ARCH) \
1405 || defined(m68k_TARGET_ARCH) \
1406 || defined(mips_TARGET_ARCH) \
1407 || defined(powerpc_TARGET_ARCH) \
1408 || defined(rs6000_TARGET_ARCH) \
1409 || defined(sparc_TARGET_ARCH)