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]
48 machdepCCOpts, picCCOpts,
51 #include "HsVersions.h"
53 import Module ( Module, mkModuleName, mkModule )
55 import PrelNames ( mAIN )
56 #ifdef i386_TARGET_ARCH
57 import StaticFlags ( opt_Static )
59 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
61 import {-# SOURCE #-} Packages (PackageState)
62 import DriverPhases ( Phase(..), phaseInputExt )
65 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
66 import Panic ( panic, GhcException(..) )
67 import UniqFM ( UniqFM )
68 import Util ( notNull, splitLongestPrefix, normalisePath )
69 import Maybes ( fromJust, orElse )
70 import SrcLoc ( SrcSpan )
72 import DATA_IOREF ( readIORef )
73 import EXCEPTION ( throwDyn )
75 #ifdef mingw32_TARGET_OS
76 import Data.List ( isPrefixOf )
81 import Char ( isDigit, isUpper )
83 import System.IO ( hPutStrLn, stderr )
84 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
86 -- -----------------------------------------------------------------------------
99 | Opt_D_dump_inlinings
100 | Opt_D_dump_occur_anal
104 | Opt_D_dump_simpl_iterations
113 | Opt_D_dump_worker_wrapper
114 | Opt_D_dump_rn_trace
115 | Opt_D_dump_rn_stats
117 | Opt_D_dump_simpl_stats
118 | Opt_D_dump_tc_trace
119 | Opt_D_dump_if_trace
124 | Opt_D_verbose_core2core
125 | Opt_D_verbose_stg2stg
127 | Opt_D_dump_hi_diffs
128 | Opt_D_dump_minimal_imports
129 | Opt_D_faststring_stats
134 | Opt_WarnIsError -- -Werror; makes warnings fatal
135 | Opt_WarnDuplicateExports
137 | Opt_WarnIncompletePatterns
138 | Opt_WarnIncompletePatternsRecUpd
139 | Opt_WarnMissingFields
140 | Opt_WarnMissingMethods
141 | Opt_WarnMissingSigs
142 | Opt_WarnNameShadowing
143 | Opt_WarnOverlappingPatterns
144 | Opt_WarnSimplePatterns
145 | Opt_WarnTypeDefaults
146 | Opt_WarnUnusedBinds
147 | Opt_WarnUnusedImports
148 | Opt_WarnUnusedMatches
149 | Opt_WarnDeprecations
150 | Opt_WarnDodgyImports
154 | Opt_AllowOverlappingInstances
155 | Opt_AllowUndecidableInstances
156 | Opt_AllowIncoherentInstances
157 | Opt_MonomorphismRestriction
159 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
162 | Opt_PArr -- Syntactic support for parallel arrays
163 | Opt_Arrows -- Arrow-notation syntax
167 | Opt_ImplicitPrelude
168 | Opt_ScopedTypeVariables
176 | Opt_IgnoreInterfacePragmas
177 | Opt_OmitInterfacePragmas
178 | Opt_DoLambdaEtaExpansion
180 | Opt_IgnoreBreakpoints
183 | Opt_UnboxStrictFields
192 | Opt_ExcessPrecision
193 | Opt_ReadUserPackageConf
197 | Opt_HideAllPackages
198 | Opt_PrintBindResult
209 data DynFlags = DynFlags {
212 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
213 stgToDo :: Maybe [StgToDo], -- similarly
214 hscTarget :: HscTarget,
215 hscOutName :: String, -- name of the output file
216 extCoreName :: String, -- name of the .core output file
217 verbosity :: Int, -- verbosity level
218 optLevel :: Int, -- optimisation level
219 maxSimplIterations :: Int, -- max simplifier iterations
220 ruleCheck :: Maybe String,
221 stolen_x86_regs :: Int,
222 cmdlineHcIncludes :: [String], -- -#includes
223 importPaths :: [FilePath],
225 mainFunIs :: Maybe String,
226 ctxtStkDepth :: Int, -- Typechecker context stack depth
228 thisPackage :: PackageId,
231 wayNames :: [WayName], -- way flags from the cmd line
232 buildTag :: String, -- the global "way" (eg. "p" for prof)
233 rtsBuildTag :: String, -- the RTS "way"
236 objectDir :: Maybe String,
237 hiDir :: Maybe String,
238 stubDir :: Maybe String,
244 outputFile :: Maybe String,
245 outputHi :: Maybe String,
247 includePaths :: [String],
248 libraryPaths :: [String],
249 frameworkPaths :: [String], -- used on darwin only
250 cmdlineFrameworks :: [String], -- ditto
251 tmpDir :: String, -- no trailing '/'
253 ghcUsagePath :: FilePath, -- Filled in by SysTools
254 ghciUsagePath :: FilePath, -- ditto
256 -- options for particular phases
267 -- commands for particular phases
269 pgm_P :: (String,[Option]),
271 pgm_c :: (String,[Option]),
272 pgm_m :: (String,[Option]),
273 pgm_s :: (String,[Option]),
274 pgm_a :: (String,[Option]),
275 pgm_l :: (String,[Option]),
276 pgm_dll :: (String,[Option]),
278 pgm_sysman :: String,
281 extraPkgConfs :: [FilePath],
282 topDir :: FilePath, -- filled in by SysTools
283 systemPackageConfig :: FilePath, -- ditto
284 -- The -package-conf flags given on the command line, in the order
287 packageFlags :: [PackageFlag],
288 -- The -package and -hide-package flags from the command-line
291 -- NB. do not modify this field, it is calculated by
292 -- Packages.initPackages and Packages.updatePackages.
293 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
294 pkgState :: PackageState,
300 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
313 = BatchCompile -- | @ghc --make Main@
314 | Interactive -- | @ghc --interactive@
315 | OneShot -- | @ghc -c Foo.hs@
316 | JustTypecheck -- | Development environemnts, refactorer, etc.
320 isOneShot :: GhcMode -> Bool
321 isOneShot OneShot = True
322 isOneShot _other = False
324 data GhcLink -- What to do in the link step, if there is one
325 = -- Only relevant for modes
326 -- DoMake and StopBefore StopLn
327 NoLink -- Don't link at all
328 | StaticLink -- Ordinary linker [the default]
329 | MkDLL -- Make a DLL
331 isNoLink :: GhcLink -> Bool
332 isNoLink NoLink = True
333 isNoLink other = False
336 = ExposePackage String
338 | IgnorePackage String
342 | cGhcWithNativeCodeGen == "YES" = HscAsm
345 initDynFlags dflags = do
346 -- someday these will be dynamic flags
347 ways <- readIORef v_Ways
348 build_tag <- readIORef v_Build_tag
349 rts_build_tag <- readIORef v_RTS_Build_tag
352 buildTag = build_tag,
353 rtsBuildTag = rts_build_tag
359 ghcLink = StaticLink,
362 hscTarget = defaultHscTarget,
367 maxSimplIterations = 4,
370 cmdlineHcIncludes = [],
374 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
376 thisPackage = mainPackageId,
382 objectSuf = phaseInputExt StopLn,
383 hcSuf = phaseInputExt HCc,
386 outputFile = Nothing,
391 cmdlineFrameworks = [],
392 tmpDir = cDEFAULT_TMPDIR,
406 pkgDatabase = Nothing,
407 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
410 Opt_ReadUserPackageConf,
412 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
413 -- behaviour the default, to see if anyone notices
417 Opt_MonomorphismRestriction,
419 -- strictness is on by default, but this only
421 Opt_CSE, -- similarly for CSE.
422 Opt_FullLaziness, -- ...and for full laziness
424 Opt_DoLambdaEtaExpansion,
425 -- This one is important for a tiresome reason:
426 -- we want to make sure that the bindings for data
427 -- constructors are eta-expanded. This is probably
428 -- a good thing anyway, but it seems fragile.
432 -- and the default no-optimisation options:
433 Opt_IgnoreInterfacePragmas,
434 Opt_OmitInterfacePragmas,
438 ] ++ standardWarnings,
440 log_action = \severity srcSpan style msg ->
442 SevInfo -> hPutStrLn stderr (show (msg style))
443 SevFatal -> hPutStrLn stderr (show (msg style))
444 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
450 0 | print errors & warnings only
451 1 | minimal verbosity: print "compiling M ... done." for each module.
452 2 | equivalent to -dshow-passes
453 3 | equivalent to existing "ghc -v"
454 4 | "ghc -v -ddump-most"
455 5 | "ghc -v -ddump-all"
458 dopt :: DynFlag -> DynFlags -> Bool
459 dopt f dflags = f `elem` (flags dflags)
461 dopt_set :: DynFlags -> DynFlag -> DynFlags
462 dopt_set dfs f = dfs{ flags = f : flags dfs }
464 dopt_unset :: DynFlags -> DynFlag -> DynFlags
465 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
467 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
468 getOpts dflags opts = reverse (opts dflags)
469 -- We add to the options from the front, so we need to reverse the list
471 getVerbFlag :: DynFlags -> String
473 | verbosity dflags >= 3 = "-v"
476 setObjectDir f d = d{ objectDir = f}
477 setHiDir f d = d{ hiDir = f}
478 setStubDir f d = d{ stubDir = f}
480 setObjectSuf f d = d{ objectSuf = f}
481 setHiSuf f d = d{ hiSuf = f}
482 setHcSuf f d = d{ hcSuf = f}
484 setOutputFile f d = d{ outputFile = f}
485 setOutputHi f d = d{ outputHi = f}
487 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
488 -- Config.hs should really use Option.
489 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
491 setPgmL f d = d{ pgm_L = f}
492 setPgmF f d = d{ pgm_F = f}
493 setPgmc f d = d{ pgm_c = (f,[])}
494 setPgmm f d = d{ pgm_m = (f,[])}
495 setPgms f d = d{ pgm_s = (f,[])}
496 setPgma f d = d{ pgm_a = (f,[])}
497 setPgml f d = d{ pgm_l = (f,[])}
498 setPgmdll f d = d{ pgm_dll = (f,[])}
500 addOptL f d = d{ opt_L = f : opt_L d}
501 addOptP f d = d{ opt_P = f : opt_P d}
502 addOptF f d = d{ opt_F = f : opt_F d}
503 addOptc f d = d{ opt_c = f : opt_c d}
504 addOptm f d = d{ opt_m = f : opt_m d}
505 addOpta f d = d{ opt_a = f : opt_a d}
506 addOptl f d = d{ opt_l = f : opt_l d}
507 addOptdll f d = d{ opt_dll = f : opt_dll d}
508 addOptdep f d = d{ opt_dep = f : opt_dep d}
510 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
512 -- -----------------------------------------------------------------------------
513 -- Command-line options
515 -- When invoking external tools as part of the compilation pipeline, we
516 -- pass these a sequence of options on the command-line. Rather than
517 -- just using a list of Strings, we use a type that allows us to distinguish
518 -- between filepaths and 'other stuff'. [The reason being, of course, that
519 -- this type gives us a handle on transforming filenames, and filenames only,
520 -- to whatever format they're expected to be on a particular platform.]
523 = FileOption -- an entry that _contains_ filename(s) / filepaths.
524 String -- a non-filepath prefix that shouldn't be
525 -- transformed (e.g., "/out=")
526 String -- the filepath/filename portion
529 -----------------------------------------------------------------------------
530 -- Setting the optimisation level
532 updOptLevel :: Int -> DynFlags -> DynFlags
533 -- Set dynflags appropriate to the optimisation level
536 then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
537 else dfs2{ optLevel = n }
539 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
540 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
543 | n == 0 = opt_0_dopts
544 | otherwise = opt_1_dopts
547 | n == 0 = opt_1_dopts
548 | otherwise = opt_0_dopts
551 Opt_IgnoreInterfacePragmas,
552 Opt_OmitInterfacePragmas
561 -- -----------------------------------------------------------------------------
562 -- Standard sets of warning options
565 = [ Opt_WarnDeprecations,
566 Opt_WarnOverlappingPatterns,
567 Opt_WarnMissingFields,
568 Opt_WarnMissingMethods,
569 Opt_WarnDuplicateExports
573 = standardWarnings ++
574 [ Opt_WarnUnusedBinds,
575 Opt_WarnUnusedMatches,
576 Opt_WarnUnusedImports,
577 Opt_WarnIncompletePatterns,
583 [ Opt_WarnTypeDefaults,
584 Opt_WarnNameShadowing,
590 -- -----------------------------------------------------------------------------
591 -- CoreToDo: abstraction of core-to-core passes to run.
593 data CoreToDo -- These are diff core-to-core passes,
594 -- which may be invoked in any order,
595 -- as many times as you like.
597 = CoreDoSimplify -- The core-to-core simplifier.
600 -- Each run of the simplifier can take a different
601 -- set of simplifier-specific flags.
603 | CoreDoFloatOutwards FloatOutSwitches
608 | CoreDoWorkerWrapper
611 | CoreDoOldStrictness
614 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
615 -- matching this string
617 | CoreDoNothing -- useful when building up lists of these things
619 data SimplifierMode -- See comments in SimplMonad
623 data SimplifierSwitch
624 = MaxSimplifierIterations Int
627 data FloatOutSwitches
628 = FloatOutSw Bool -- True <=> float lambdas to top level
629 Bool -- True <=> float constants to top level,
630 -- even if they do not escape a lambda
633 -- The core-to-core pass ordering is derived from the DynFlags:
635 getCoreToDo :: DynFlags -> [CoreToDo]
637 | Just todo <- coreToDo dflags = todo -- set explicitly by user
638 | otherwise = core_todo
640 opt_level = optLevel dflags
641 max_iter = maxSimplIterations dflags
642 strictness = dopt Opt_Strictness dflags
643 full_laziness = dopt Opt_FullLaziness dflags
644 cse = dopt Opt_CSE dflags
645 rule_check = ruleCheck dflags
648 if opt_level == 0 then
650 CoreDoSimplify (SimplPhase 0) [
651 MaxSimplifierIterations max_iter
654 else {- opt_level >= 1 -} [
656 -- initial simplify: mk specialiser happy: minimum effort please
657 CoreDoSimplify SimplGently [
659 -- Don't inline anything till full laziness has bitten
660 -- In particular, inlining wrappers inhibits floating
661 -- e.g. ...(case f x of ...)...
662 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
663 -- ==> ...(case x of I# x# -> case fw x# of ...)...
664 -- and now the redex (f x) isn't floatable any more
665 -- Similarly, don't apply any rules until after full
666 -- laziness. Notably, list fusion can prevent floating.
668 NoCaseOfCase, -- Don't do case-of-case transformations.
669 -- This makes full laziness work better
670 MaxSimplifierIterations max_iter
673 -- Specialisation is best done before full laziness
674 -- so that overloaded functions have all their dictionary lambdas manifest
677 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
682 CoreDoSimplify (SimplPhase 2) [
683 -- Want to run with inline phase 2 after the specialiser to give
684 -- maximum chance for fusion to work before we inline build/augment
685 -- in phase 1. This made a difference in 'ansi' where an
686 -- overloaded function wasn't inlined till too late.
687 MaxSimplifierIterations max_iter
689 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
691 CoreDoSimplify (SimplPhase 1) [
692 -- Need inline-phase2 here so that build/augment get
693 -- inlined. I found that spectral/hartel/genfft lost some useful
694 -- strictness in the function sumcode' if augment is not inlined
695 -- before strictness analysis runs
696 MaxSimplifierIterations max_iter
698 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
700 CoreDoSimplify (SimplPhase 0) [
701 -- Phase 0: allow all Ids to be inlined now
702 -- This gets foldr inlined before strictness analysis
704 MaxSimplifierIterations 3
705 -- At least 3 iterations because otherwise we land up with
706 -- huge dead expressions because of an infelicity in the
708 -- let k = BIG in foldr k z xs
709 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
710 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
714 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
716 #ifdef OLD_STRICTNESS
719 if strictness then CoreDoStrictness else CoreDoNothing,
723 CoreDoSimplify (SimplPhase 0) [
724 MaxSimplifierIterations max_iter
727 if full_laziness then
728 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
729 True) -- Float constants
731 -- nofib/spectral/hartel/wang doubles in speed if you
732 -- do full laziness late in the day. It only happens
733 -- after fusion and other stuff, so the early pass doesn't
734 -- catch it. For the record, the redex is
735 -- f_el22 (f_el21 r_midblock)
738 -- We want CSE to follow the final full-laziness pass, because it may
739 -- succeed in commoning up things floated out by full laziness.
740 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
742 if cse then CoreCSE else CoreDoNothing,
746 -- Case-liberation for -O2. This should be after
747 -- strictness analysis and the simplification which follows it.
749 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
754 (if opt_level >= 2 then
756 CoreDoSimplify (SimplPhase 0) [
757 MaxSimplifierIterations max_iter
758 ], -- Run the simplifier after LiberateCase to vastly
759 -- reduce the possiblility of shadowing
760 -- Reason: see Note [Shadowing] in SpecConstr.lhs
768 -- Final clean-up simplification:
769 [ CoreDoSimplify (SimplPhase 0) [
770 MaxSimplifierIterations max_iter
774 -- -----------------------------------------------------------------------------
775 -- StgToDo: abstraction of stg-to-stg passes to run.
778 = StgDoMassageForProfiling -- should be (next to) last
779 -- There's also setStgVarInfo, but its absolute "lastness"
780 -- is so critical that it is hardwired in (no flag).
783 getStgToDo :: DynFlags -> [StgToDo]
785 | Just todo <- stgToDo dflags = todo -- set explicitly by user
788 stg_stats = dopt Opt_StgStats dflags
790 todo1 = if stg_stats then [D_stg_stats] else []
792 todo2 | WayProf `elem` wayNames dflags
793 = StgDoMassageForProfiling : todo1
797 -- -----------------------------------------------------------------------------
801 allFlags = map ('-':) $
802 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
803 map ("fno-"++) flags ++
805 where ok (PrefixPred _ _) = False
807 flags = map fst fFlags
809 dynamic_flags :: [(String, OptKind DynP)]
811 ( "n" , NoArg (setDynFlag Opt_DryRun) )
812 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
813 , ( "F" , NoArg (setDynFlag Opt_Pp))
814 , ( "#include" , HasArg (addCmdlineHCInclude) )
815 , ( "v" , OptIntSuffix setVerbosity )
817 ------- Specific phases --------------------------------------------
818 , ( "pgmL" , HasArg (upd . setPgmL) )
819 , ( "pgmP" , HasArg (upd . setPgmP) )
820 , ( "pgmF" , HasArg (upd . setPgmF) )
821 , ( "pgmc" , HasArg (upd . setPgmc) )
822 , ( "pgmm" , HasArg (upd . setPgmm) )
823 , ( "pgms" , HasArg (upd . setPgms) )
824 , ( "pgma" , HasArg (upd . setPgma) )
825 , ( "pgml" , HasArg (upd . setPgml) )
826 , ( "pgmdll" , HasArg (upd . setPgmdll) )
828 , ( "optL" , HasArg (upd . addOptL) )
829 , ( "optP" , HasArg (upd . addOptP) )
830 , ( "optF" , HasArg (upd . addOptF) )
831 , ( "optc" , HasArg (upd . addOptc) )
832 , ( "optm" , HasArg (upd . addOptm) )
833 , ( "opta" , HasArg (upd . addOpta) )
834 , ( "optl" , HasArg (upd . addOptl) )
835 , ( "optdll" , HasArg (upd . addOptdll) )
836 , ( "optdep" , HasArg (upd . addOptdep) )
838 , ( "split-objs" , NoArg (if can_split
839 then setDynFlag Opt_SplitObjs
842 -------- Linking ----------------------------------------------------
843 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
844 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
845 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
847 ------- Libraries ---------------------------------------------------
848 , ( "L" , Prefix addLibraryPath )
849 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
852 ------- Frameworks --------------------------------------------------
853 -- -framework-path should really be -F ...
854 , ( "framework-path" , HasArg addFrameworkPath )
855 , ( "framework" , HasArg (upd . addCmdlineFramework) )
857 ------- Output Redirection ------------------------------------------
858 , ( "odir" , HasArg (upd . setObjectDir . Just))
859 , ( "o" , SepArg (upd . setOutputFile . Just))
860 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
861 , ( "osuf" , HasArg (upd . setObjectSuf))
862 , ( "hcsuf" , HasArg (upd . setHcSuf))
863 , ( "hisuf" , HasArg (upd . setHiSuf))
864 , ( "hidir" , HasArg (upd . setHiDir . Just))
865 , ( "tmpdir" , HasArg (upd . setTmpDir))
866 , ( "stubdir" , HasArg (upd . setStubDir . Just))
868 ------- Keeping temporary files -------------------------------------
869 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
870 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
871 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
872 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
874 ------- Miscellaneous ----------------------------------------------
875 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
876 , ( "main-is" , SepArg setMainIs )
878 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
879 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
880 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
882 ------- Packages ----------------------------------------------------
883 , ( "package-conf" , HasArg extraPkgConf_ )
884 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
885 , ( "package-name" , HasArg setPackageName )
886 , ( "package" , HasArg exposePackage )
887 , ( "hide-package" , HasArg hidePackage )
888 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
889 , ( "ignore-package" , HasArg ignorePackage )
890 , ( "syslib" , HasArg exposePackage ) -- for compatibility
892 ------ HsCpp opts ---------------------------------------------------
893 , ( "D", AnySuffix (upd . addOptP) )
894 , ( "U", AnySuffix (upd . addOptP) )
896 ------- Include/Import Paths ----------------------------------------
897 , ( "I" , Prefix addIncludePath)
898 , ( "i" , OptPrefix addImportPath )
900 ------ Debugging ----------------------------------------------------
901 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
903 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
904 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
905 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
906 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
907 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
908 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
909 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
910 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
911 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
912 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
913 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
914 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
915 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
916 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
917 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
918 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
919 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
920 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
921 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
922 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
923 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
924 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
925 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
926 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
927 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
928 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
929 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
930 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
931 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
932 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
933 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
934 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
935 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
936 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
937 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
938 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
939 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
940 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
941 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
942 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
943 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
944 setVerbosity (Just 2)) )
945 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
947 ------ Machine dependant (-m<blah>) stuff ---------------------------
949 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
950 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
951 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
953 ------ Warning opts -------------------------------------------------
954 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
955 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
956 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
957 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
958 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
960 ------ Optimisation flags ------------------------------------------
961 , ( "O" , NoArg (upd (setOptLevel 1)))
962 , ( "Onot" , NoArg (upd (setOptLevel 0)))
963 , ( "O" , PrefixPred (all isDigit)
964 (\f -> upd (setOptLevel (read f))))
966 , ( "fmax-simplifier-iterations",
967 PrefixPred (all isDigit)
969 dfs{ maxSimplIterations = read n })) )
972 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
974 ------ Compiler flags -----------------------------------------------
976 , ( "fno-code", NoArg (setTarget HscNothing))
977 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
978 , ( "fvia-c", NoArg (setTarget HscC) )
979 , ( "fvia-C", NoArg (setTarget HscC) )
980 , ( "filx", NoArg (setTarget HscILX) )
982 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
983 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
985 , ( "fcontext-stack" , OptIntSuffix $ \mb_n -> upd $ \dfs ->
986 dfs{ ctxtStkDepth = mb_n `orElse` 3 })
988 -- the rest of the -f* and -fno-* flags
989 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
990 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
993 -- these -f<blah> flags can all be reversed with -fno-<blah>
996 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
997 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
998 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
999 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1000 ( "warn-missing-fields", Opt_WarnMissingFields ),
1001 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1002 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1003 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1004 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1005 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1006 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1007 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1008 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1009 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1010 ( "warn-deprecations", Opt_WarnDeprecations ),
1011 ( "warn-orphans", Opt_WarnOrphans ),
1012 ( "fi", Opt_FFI ), -- support `-ffi'...
1013 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
1014 ( "arrows", Opt_Arrows ), -- arrow syntax
1015 ( "parr", Opt_PArr ),
1017 ( "implicit-prelude", Opt_ImplicitPrelude ),
1018 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1019 ( "bang-patterns", Opt_BangPatterns ),
1020 ( "indexed-types", Opt_IndexedTypes ),
1021 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1022 ( "mono-pat-binds", Opt_MonoPatBinds ),
1023 ( "extended-default-rules", Opt_ExtendedDefaultRules ),
1024 ( "implicit-params", Opt_ImplicitParams ),
1025 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
1026 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
1027 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
1028 ( "generics", Opt_Generics ),
1029 ( "strictness", Opt_Strictness ),
1030 ( "full-laziness", Opt_FullLaziness ),
1032 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1033 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1034 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1035 ( "ignore-asserts", Opt_IgnoreAsserts ),
1036 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1037 ( "do-eta-reduction", Opt_DoEtaReduction ),
1038 ( "case-merge", Opt_CaseMerge ),
1039 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1040 ( "dicts-cheap", Opt_DictsCheap ),
1041 ( "excess-precision", Opt_ExcessPrecision ),
1042 ( "asm-mangling", Opt_DoAsmMangling ),
1043 ( "print-bind-result", Opt_PrintBindResult ),
1044 ( "force-recomp", Opt_ForceRecomp )
1048 glasgowExtsFlags = [
1052 Opt_ScopedTypeVariables,
1055 isFFlag f = f `elem` (map fst fFlags)
1056 getFFlag f = fromJust (lookup f fFlags)
1058 -- -----------------------------------------------------------------------------
1059 -- Parsing the dynamic flags.
1061 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1062 parseDynamicFlags dflags args = do
1063 let ((leftover,errs),dflags')
1064 = runCmdLine (processArgs dynamic_flags args) dflags
1065 when (not (null errs)) $ do
1066 throwDyn (UsageError (unlines errs))
1067 return (dflags', leftover)
1070 type DynP = CmdLineP DynFlags
1072 upd :: (DynFlags -> DynFlags) -> DynP ()
1074 dfs <- getCmdLineState
1075 putCmdLineState $! (f dfs)
1077 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1078 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1079 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1081 setDumpFlag :: DynFlag -> OptKind DynP
1082 setDumpFlag dump_flag
1083 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1084 -- Whenver we -ddump, switch off the recompilation checker,
1085 -- else you don't see the dump!
1087 setVerbosity :: Maybe Int -> DynP ()
1088 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1090 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1092 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1095 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1097 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1099 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1101 | Nothing <- unpackPackageId pid
1102 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1104 = upd (\s -> s{ thisPackage = pid })
1106 pid = stringToPackageId p
1108 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags
1109 -- (-fvia-C, -fasm, -filx respectively).
1110 setTarget l = upd (\dfs -> case hscTarget dfs of
1111 HscC -> dfs{ hscTarget = l }
1112 HscAsm -> dfs{ hscTarget = l }
1113 HscILX -> dfs{ hscTarget = l }
1116 setOptLevel :: Int -> DynFlags -> DynFlags
1117 setOptLevel n dflags
1118 | hscTarget dflags == HscInterpreted && n > 0
1120 -- not in IO any more, oh well:
1121 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1123 = updOptLevel n dflags
1126 setMainIs :: String -> DynP ()
1128 | not (null main_fn) -- The arg looked like "Foo.baz"
1129 = upd $ \d -> d{ mainFunIs = Just main_fn,
1130 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1132 | isUpper (head main_mod) -- The arg looked like "Foo"
1133 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1135 | otherwise -- The arg looked like "baz"
1136 = upd $ \d -> d{ mainFunIs = Just main_mod }
1138 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1140 -----------------------------------------------------------------------------
1141 -- Paths & Libraries
1143 -- -i on its own deletes the import paths
1144 addImportPath "" = upd (\s -> s{importPaths = []})
1145 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1149 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1152 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1154 addFrameworkPath p =
1155 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1157 split_marker = ':' -- not configurable (ToDo)
1159 splitPathList :: String -> [String]
1160 splitPathList s = filter notNull (splitUp s)
1161 -- empty paths are ignored: there might be a trailing
1162 -- ':' in the initial list, for example. Empty paths can
1163 -- cause confusion when they are translated into -I options
1164 -- for passing to gcc.
1166 #ifndef mingw32_TARGET_OS
1167 splitUp xs = split split_marker xs
1169 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1171 -- That is, if "foo:bar:baz" is used, this interpreted as
1172 -- consisting of three entries, 'foo', 'bar', 'baz'.
1173 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1174 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1176 -- Notice that no attempt is made to fully replace the 'standard'
1177 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1178 -- that this will cause too much breakage for users & ':' will
1179 -- work fine even with DOS paths, if you're not insisting on being silly.
1182 splitUp (x:':':div:xs) | div `elem` dir_markers
1183 = ((x:':':div:p): splitUp rs)
1185 (p,rs) = findNextPath xs
1186 -- we used to check for existence of the path here, but that
1187 -- required the IO monad to be threaded through the command-line
1188 -- parser which is quite inconvenient. The
1189 splitUp xs = cons p (splitUp rs)
1191 (p,rs) = findNextPath xs
1196 -- will be called either when we've consumed nought or the
1197 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1198 -- finding the next split marker.
1200 case break (`elem` split_markers) xs of
1201 (p, d:ds) -> (p, ds)
1204 split_markers :: [Char]
1205 split_markers = [':', ';']
1207 dir_markers :: [Char]
1208 dir_markers = ['/', '\\']
1211 -- -----------------------------------------------------------------------------
1212 -- tmpDir, where we store temporary files.
1214 setTmpDir :: FilePath -> DynFlags -> DynFlags
1215 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1217 #if !defined(mingw32_HOST_OS)
1218 canonicalise p = normalisePath p
1220 -- Canonicalisation of temp path under win32 is a bit more
1221 -- involved: (a) strip trailing slash,
1222 -- (b) normalise slashes
1223 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1225 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1227 -- if we're operating under cygwin, and TMP/TEMP is of
1228 -- the form "/cygdrive/drive/path", translate this to
1229 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1230 -- understand /cygdrive paths.)
1232 | "/cygdrive/" `isPrefixOf` path =
1233 case drop (length "/cygdrive/") path of
1234 drive:xs@('/':_) -> drive:':':xs
1238 -- strip the trailing backslash (awful, but we only do this once).
1239 removeTrailingSlash path =
1246 -----------------------------------------------------------------------------
1247 -- Via-C compilation stuff
1249 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1250 [String]) -- for registerised HC compilations
1251 machdepCCOpts dflags
1252 #if alpha_TARGET_ARCH
1254 #ifdef HAVE_THREADED_RTS_SUPPORT
1258 -- For now, to suppress the gcc warning "call-clobbered
1259 -- register used for global register variable", we simply
1260 -- disable all warnings altogether using the -w flag. Oh well.
1262 #elif hppa_TARGET_ARCH
1263 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1264 -- (very nice, but too bad the HP /usr/include files don't agree.)
1265 = ( ["-D_HPUX_SOURCE"], [] )
1267 #elif m68k_TARGET_ARCH
1268 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1269 -- popping of args to routines to be explicit; if we let things
1270 -- be deferred 'til after an STGJUMP, imminent death is certain!
1272 -- -fomit-frame-pointer : *don't*
1273 -- It's better to have a6 completely tied up being a frame pointer
1274 -- rather than let GCC pick random things to do with it.
1275 -- (If we want to steal a6, then we would try to do things
1276 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1277 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1279 #elif i386_TARGET_ARCH
1280 -- -fno-defer-pop : basically the same game as for m68k
1282 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1283 -- the fp (%ebp) for our register maps.
1284 = let n_regs = stolen_x86_regs dflags
1287 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1288 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1291 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1292 -- Some gccs are configured with
1293 -- -momit-leaf-frame-pointer on by default, and it
1294 -- apparently takes precedence over
1295 -- -fomit-frame-pointer, so we disable it first here.
1296 "-mno-omit-leaf-frame-pointer",
1298 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1299 "-fno-unit-at-a-time",
1300 -- unit-at-a-time doesn't do us any good, and screws
1301 -- up -split-objs by moving the split markers around.
1302 -- It's only turned on with -O2, but put it here just
1303 -- in case someone uses -optc-O2.
1305 "-fomit-frame-pointer",
1306 -- we want -fno-builtin, because when gcc inlines
1307 -- built-in functions like memcpy() it tends to
1308 -- run out of registers, requiring -monly-n-regs
1310 "-DSTOLEN_X86_REGS="++show n_regs ]
1313 #elif ia64_TARGET_ARCH
1314 = ( [], ["-fomit-frame-pointer", "-G0"] )
1316 #elif x86_64_TARGET_ARCH
1317 = ( [], ["-fomit-frame-pointer",
1318 "-fno-asynchronous-unwind-tables",
1319 -- the unwind tables are unnecessary for HC code,
1320 -- and get in the way of -split-objs. Another option
1321 -- would be to throw them away in the mangler, but this
1323 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1324 "-fno-unit-at-a-time",
1325 -- unit-at-a-time doesn't do us any good, and screws
1326 -- up -split-objs by moving the split markers around.
1327 -- It's only turned on with -O2, but put it here just
1328 -- in case someone uses -optc-O2.
1331 -- calling builtins like strlen() using the FFI can
1332 -- cause gcc to run out of regs, so use the external
1336 #elif mips_TARGET_ARCH
1337 = ( ["-static"], [] )
1339 #elif sparc_TARGET_ARCH
1341 -- For now, to suppress the gcc warning "call-clobbered
1342 -- register used for global register variable", we simply
1343 -- disable all warnings altogether using the -w flag. Oh well.
1345 #elif powerpc_apple_darwin_TARGET
1347 -- Disable Apple's precompiling preprocessor. It's a great thing
1348 -- for "normal" programs, but it doesn't support register variable
1350 = ( [], ["-no-cpp-precomp"] )
1355 picCCOpts :: DynFlags -> [String]
1357 #if darwin_TARGET_OS
1358 -- Apple prefers to do things the other way round.
1359 -- PIC is on by default.
1360 -- -mdynamic-no-pic:
1361 -- Turn off PIC code generation.
1363 -- Don't generate "common" symbols - these are unwanted
1364 -- in dynamic libraries.
1369 = ["-mdynamic-no-pic"]
1370 #elif mingw32_TARGET_OS
1371 -- no -fPIC for Windows
1380 -- -----------------------------------------------------------------------------
1385 #if defined(i386_TARGET_ARCH) \
1386 || defined(x86_64_TARGET_ARCH) \
1387 || defined(alpha_TARGET_ARCH) \
1388 || defined(hppa_TARGET_ARCH) \
1389 || defined(m68k_TARGET_ARCH) \
1390 || defined(mips_TARGET_ARCH) \
1391 || defined(powerpc_TARGET_ARCH) \
1392 || defined(rs6000_TARGET_ARCH) \
1393 || defined(sparc_TARGET_ARCH)