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 -- -----------------------------------------------------------------------------
100 | Opt_D_dump_inlinings
101 | Opt_D_dump_occur_anal
105 | Opt_D_dump_simpl_iterations
114 | Opt_D_dump_worker_wrapper
115 | Opt_D_dump_rn_trace
116 | Opt_D_dump_rn_stats
118 | Opt_D_dump_simpl_stats
119 | Opt_D_dump_tc_trace
120 | Opt_D_dump_if_trace
126 | Opt_D_verbose_core2core
127 | Opt_D_verbose_stg2stg
129 | Opt_D_dump_hi_diffs
130 | Opt_D_dump_minimal_imports
131 | Opt_D_faststring_stats
136 | Opt_WarnIsError -- -Werror; makes warnings fatal
137 | Opt_WarnDuplicateExports
139 | Opt_WarnIncompletePatterns
140 | Opt_WarnIncompletePatternsRecUpd
141 | Opt_WarnMissingFields
142 | Opt_WarnMissingMethods
143 | Opt_WarnMissingSigs
144 | Opt_WarnNameShadowing
145 | Opt_WarnOverlappingPatterns
146 | Opt_WarnSimplePatterns
147 | Opt_WarnTypeDefaults
148 | Opt_WarnUnusedBinds
149 | Opt_WarnUnusedImports
150 | Opt_WarnUnusedMatches
151 | Opt_WarnDeprecations
152 | Opt_WarnDodgyImports
156 | Opt_AllowOverlappingInstances
157 | Opt_AllowUndecidableInstances
158 | Opt_AllowIncoherentInstances
159 | Opt_MonomorphismRestriction
161 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
164 | Opt_PArr -- Syntactic support for parallel arrays
165 | Opt_Arrows -- Arrow-notation syntax
169 | Opt_ImplicitPrelude
170 | Opt_ScopedTypeVariables
178 | Opt_IgnoreInterfacePragmas
179 | Opt_OmitInterfacePragmas
180 | Opt_DoLambdaEtaExpansion
182 | Opt_IgnoreBreakpoints
185 | Opt_UnboxStrictFields
194 | Opt_ExcessPrecision
195 | Opt_ReadUserPackageConf
199 | Opt_HideAllPackages
200 | Opt_PrintBindResult
212 data DynFlags = DynFlags {
215 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
216 stgToDo :: Maybe [StgToDo], -- similarly
217 hscTarget :: HscTarget,
218 hscOutName :: String, -- name of the output file
219 extCoreName :: String, -- name of the .core output file
220 verbosity :: Int, -- verbosity level
221 optLevel :: Int, -- optimisation level
222 maxSimplIterations :: Int, -- max simplifier iterations
223 ruleCheck :: Maybe String,
224 stolen_x86_regs :: Int,
225 cmdlineHcIncludes :: [String], -- -#includes
226 importPaths :: [FilePath],
228 mainFunIs :: Maybe String,
229 ctxtStkDepth :: Int, -- Typechecker context stack depth
231 thisPackage :: PackageId,
234 wayNames :: [WayName], -- way flags from the cmd line
235 buildTag :: String, -- the global "way" (eg. "p" for prof)
236 rtsBuildTag :: String, -- the RTS "way"
239 objectDir :: Maybe String,
240 hiDir :: Maybe String,
241 stubDir :: Maybe String,
247 outputFile :: Maybe String,
248 outputHi :: Maybe String,
250 includePaths :: [String],
251 libraryPaths :: [String],
252 frameworkPaths :: [String], -- used on darwin only
253 cmdlineFrameworks :: [String], -- ditto
254 tmpDir :: String, -- no trailing '/'
256 ghcUsagePath :: FilePath, -- Filled in by SysTools
257 ghciUsagePath :: FilePath, -- ditto
259 hpcDir :: String, -- ^ path to store the .mix files
261 -- options for particular phases
272 -- commands for particular phases
274 pgm_P :: (String,[Option]),
276 pgm_c :: (String,[Option]),
277 pgm_m :: (String,[Option]),
278 pgm_s :: (String,[Option]),
279 pgm_a :: (String,[Option]),
280 pgm_l :: (String,[Option]),
281 pgm_dll :: (String,[Option]),
283 pgm_sysman :: String,
286 extraPkgConfs :: [FilePath],
287 topDir :: FilePath, -- filled in by SysTools
288 systemPackageConfig :: FilePath, -- ditto
289 -- The -package-conf flags given on the command line, in the order
292 packageFlags :: [PackageFlag],
293 -- The -package and -hide-package flags from the command-line
296 -- NB. do not modify this field, it is calculated by
297 -- Packages.initPackages and Packages.updatePackages.
298 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
299 pkgState :: PackageState,
305 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
317 = BatchCompile -- | @ghc --make Main@
318 | Interactive -- | @ghc --interactive@
319 | OneShot -- | @ghc -c Foo.hs@
320 | JustTypecheck -- | Development environemnts, refactorer, etc.
324 isOneShot :: GhcMode -> Bool
325 isOneShot OneShot = True
326 isOneShot _other = False
328 data GhcLink -- What to do in the link step, if there is one
329 = -- Only relevant for modes
330 -- DoMake and StopBefore StopLn
331 NoLink -- Don't link at all
332 | StaticLink -- Ordinary linker [the default]
333 | MkDLL -- Make a DLL
335 isNoLink :: GhcLink -> Bool
336 isNoLink NoLink = True
337 isNoLink other = False
340 = ExposePackage String
342 | IgnorePackage String
346 | cGhcWithNativeCodeGen == "YES" = HscAsm
349 initDynFlags dflags = do
350 -- someday these will be dynamic flags
351 ways <- readIORef v_Ways
352 build_tag <- readIORef v_Build_tag
353 rts_build_tag <- readIORef v_RTS_Build_tag
356 buildTag = build_tag,
357 rtsBuildTag = rts_build_tag
363 ghcLink = StaticLink,
366 hscTarget = defaultHscTarget,
371 maxSimplIterations = 4,
374 cmdlineHcIncludes = [],
378 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
380 thisPackage = mainPackageId,
386 objectSuf = phaseInputExt StopLn,
387 hcSuf = phaseInputExt HCc,
390 outputFile = Nothing,
395 cmdlineFrameworks = [],
396 tmpDir = cDEFAULT_TMPDIR,
412 pkgDatabase = Nothing,
413 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
416 Opt_ReadUserPackageConf,
418 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
419 -- behaviour the default, to see if anyone notices
423 Opt_MonomorphismRestriction,
425 -- strictness is on by default, but this only
427 Opt_CSE, -- similarly for CSE.
428 Opt_FullLaziness, -- ...and for full laziness
430 Opt_DoLambdaEtaExpansion,
431 -- This one is important for a tiresome reason:
432 -- we want to make sure that the bindings for data
433 -- constructors are eta-expanded. This is probably
434 -- a good thing anyway, but it seems fragile.
438 -- and the default no-optimisation options:
439 Opt_IgnoreInterfacePragmas,
440 Opt_OmitInterfacePragmas,
444 ] ++ standardWarnings,
446 log_action = \severity srcSpan style msg ->
448 SevInfo -> hPutStrLn stderr (show (msg style))
449 SevFatal -> hPutStrLn stderr (show (msg style))
450 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
456 0 | print errors & warnings only
457 1 | minimal verbosity: print "compiling M ... done." for each module.
458 2 | equivalent to -dshow-passes
459 3 | equivalent to existing "ghc -v"
460 4 | "ghc -v -ddump-most"
461 5 | "ghc -v -ddump-all"
464 dopt :: DynFlag -> DynFlags -> Bool
465 dopt f dflags = f `elem` (flags dflags)
467 dopt_set :: DynFlags -> DynFlag -> DynFlags
468 dopt_set dfs f = dfs{ flags = f : flags dfs }
470 dopt_unset :: DynFlags -> DynFlag -> DynFlags
471 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
473 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
474 getOpts dflags opts = reverse (opts dflags)
475 -- We add to the options from the front, so we need to reverse the list
477 getVerbFlag :: DynFlags -> String
479 | verbosity dflags >= 3 = "-v"
482 setObjectDir f d = d{ objectDir = f}
483 setHiDir f d = d{ hiDir = f}
484 setStubDir f d = d{ stubDir = f}
486 setObjectSuf f d = d{ objectSuf = f}
487 setHiSuf f d = d{ hiSuf = f}
488 setHcSuf f d = d{ hcSuf = f}
490 setOutputFile f d = d{ outputFile = f}
491 setOutputHi f d = d{ outputHi = f}
493 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
494 -- Config.hs should really use Option.
495 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
497 setPgmL f d = d{ pgm_L = f}
498 setPgmF f d = d{ pgm_F = f}
499 setPgmc f d = d{ pgm_c = (f,[])}
500 setPgmm f d = d{ pgm_m = (f,[])}
501 setPgms f d = d{ pgm_s = (f,[])}
502 setPgma f d = d{ pgm_a = (f,[])}
503 setPgml f d = d{ pgm_l = (f,[])}
504 setPgmdll f d = d{ pgm_dll = (f,[])}
506 addOptL f d = d{ opt_L = f : opt_L d}
507 addOptP f d = d{ opt_P = f : opt_P d}
508 addOptF f d = d{ opt_F = f : opt_F d}
509 addOptc f d = d{ opt_c = f : opt_c d}
510 addOptm f d = d{ opt_m = f : opt_m d}
511 addOpta f d = d{ opt_a = f : opt_a d}
512 addOptl f d = d{ opt_l = f : opt_l d}
513 addOptdll f d = d{ opt_dll = f : opt_dll d}
514 addOptdep f d = d{ opt_dep = f : opt_dep d}
516 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
518 -- -----------------------------------------------------------------------------
519 -- Command-line options
521 -- When invoking external tools as part of the compilation pipeline, we
522 -- pass these a sequence of options on the command-line. Rather than
523 -- just using a list of Strings, we use a type that allows us to distinguish
524 -- between filepaths and 'other stuff'. [The reason being, of course, that
525 -- this type gives us a handle on transforming filenames, and filenames only,
526 -- to whatever format they're expected to be on a particular platform.]
529 = FileOption -- an entry that _contains_ filename(s) / filepaths.
530 String -- a non-filepath prefix that shouldn't be
531 -- transformed (e.g., "/out=")
532 String -- the filepath/filename portion
535 -----------------------------------------------------------------------------
536 -- Setting the optimisation level
538 updOptLevel :: Int -> DynFlags -> DynFlags
539 -- Set dynflags appropriate to the optimisation level
541 = dfs2{ optLevel = n }
543 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
544 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
547 | n == 0 = opt_0_dopts
548 | otherwise = opt_1_dopts
551 | n == 0 = opt_1_dopts
552 | otherwise = opt_0_dopts
555 Opt_IgnoreInterfacePragmas,
556 Opt_OmitInterfacePragmas
565 -- -----------------------------------------------------------------------------
566 -- Standard sets of warning options
569 = [ Opt_WarnDeprecations,
570 Opt_WarnOverlappingPatterns,
571 Opt_WarnMissingFields,
572 Opt_WarnMissingMethods,
573 Opt_WarnDuplicateExports
577 = standardWarnings ++
578 [ Opt_WarnUnusedBinds,
579 Opt_WarnUnusedMatches,
580 Opt_WarnUnusedImports,
581 Opt_WarnIncompletePatterns,
587 [ Opt_WarnTypeDefaults,
588 Opt_WarnNameShadowing,
594 -- -----------------------------------------------------------------------------
595 -- CoreToDo: abstraction of core-to-core passes to run.
597 data CoreToDo -- These are diff core-to-core passes,
598 -- which may be invoked in any order,
599 -- as many times as you like.
601 = CoreDoSimplify -- The core-to-core simplifier.
604 -- Each run of the simplifier can take a different
605 -- set of simplifier-specific flags.
607 | CoreDoFloatOutwards FloatOutSwitches
612 | CoreDoWorkerWrapper
615 | CoreDoOldStrictness
618 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
619 -- matching this string
621 | CoreDoNothing -- useful when building up lists of these things
623 data SimplifierMode -- See comments in SimplMonad
627 data SimplifierSwitch
628 = MaxSimplifierIterations Int
631 data FloatOutSwitches
632 = FloatOutSw Bool -- True <=> float lambdas to top level
633 Bool -- True <=> float constants to top level,
634 -- even if they do not escape a lambda
637 -- The core-to-core pass ordering is derived from the DynFlags:
639 getCoreToDo :: DynFlags -> [CoreToDo]
641 | Just todo <- coreToDo dflags = todo -- set explicitly by user
642 | otherwise = core_todo
644 opt_level = optLevel dflags
645 max_iter = maxSimplIterations dflags
646 strictness = dopt Opt_Strictness dflags
647 full_laziness = dopt Opt_FullLaziness dflags
648 cse = dopt Opt_CSE dflags
649 rule_check = ruleCheck dflags
652 if opt_level == 0 then
654 CoreDoSimplify (SimplPhase 0) [
655 MaxSimplifierIterations max_iter
658 else {- opt_level >= 1 -} [
660 -- initial simplify: mk specialiser happy: minimum effort please
661 CoreDoSimplify SimplGently [
663 -- Don't inline anything till full laziness has bitten
664 -- In particular, inlining wrappers inhibits floating
665 -- e.g. ...(case f x of ...)...
666 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
667 -- ==> ...(case x of I# x# -> case fw x# of ...)...
668 -- and now the redex (f x) isn't floatable any more
669 -- Similarly, don't apply any rules until after full
670 -- laziness. Notably, list fusion can prevent floating.
672 NoCaseOfCase, -- Don't do case-of-case transformations.
673 -- This makes full laziness work better
674 MaxSimplifierIterations max_iter
677 -- Specialisation is best done before full laziness
678 -- so that overloaded functions have all their dictionary lambdas manifest
681 if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
686 CoreDoSimplify (SimplPhase 2) [
687 -- Want to run with inline phase 2 after the specialiser to give
688 -- maximum chance for fusion to work before we inline build/augment
689 -- in phase 1. This made a difference in 'ansi' where an
690 -- overloaded function wasn't inlined till too late.
691 MaxSimplifierIterations max_iter
693 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
695 CoreDoSimplify (SimplPhase 1) [
696 -- Need inline-phase2 here so that build/augment get
697 -- inlined. I found that spectral/hartel/genfft lost some useful
698 -- strictness in the function sumcode' if augment is not inlined
699 -- before strictness analysis runs
700 MaxSimplifierIterations max_iter
702 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
704 CoreDoSimplify (SimplPhase 0) [
705 -- Phase 0: allow all Ids to be inlined now
706 -- This gets foldr inlined before strictness analysis
708 MaxSimplifierIterations 3
709 -- At least 3 iterations because otherwise we land up with
710 -- huge dead expressions because of an infelicity in the
712 -- let k = BIG in foldr k z xs
713 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
714 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
718 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
720 #ifdef OLD_STRICTNESS
723 if strictness then CoreDoStrictness else CoreDoNothing,
727 CoreDoSimplify (SimplPhase 0) [
728 MaxSimplifierIterations max_iter
731 if full_laziness then
732 CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
733 True) -- Float constants
735 -- nofib/spectral/hartel/wang doubles in speed if you
736 -- do full laziness late in the day. It only happens
737 -- after fusion and other stuff, so the early pass doesn't
738 -- catch it. For the record, the redex is
739 -- f_el22 (f_el21 r_midblock)
742 -- We want CSE to follow the final full-laziness pass, because it may
743 -- succeed in commoning up things floated out by full laziness.
744 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
746 if cse then CoreCSE else CoreDoNothing,
750 -- Case-liberation for -O2. This should be after
751 -- strictness analysis and the simplification which follows it.
753 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
758 (if opt_level >= 2 then
760 CoreDoSimplify (SimplPhase 0) [
761 MaxSimplifierIterations max_iter
762 ], -- Run the simplifier after LiberateCase to vastly
763 -- reduce the possiblility of shadowing
764 -- Reason: see Note [Shadowing] in SpecConstr.lhs
772 -- Final clean-up simplification:
773 [ CoreDoSimplify (SimplPhase 0) [
774 MaxSimplifierIterations max_iter
778 -- -----------------------------------------------------------------------------
779 -- StgToDo: abstraction of stg-to-stg passes to run.
782 = StgDoMassageForProfiling -- should be (next to) last
783 -- There's also setStgVarInfo, but its absolute "lastness"
784 -- is so critical that it is hardwired in (no flag).
787 getStgToDo :: DynFlags -> [StgToDo]
789 | Just todo <- stgToDo dflags = todo -- set explicitly by user
792 stg_stats = dopt Opt_StgStats dflags
794 todo1 = if stg_stats then [D_stg_stats] else []
796 todo2 | WayProf `elem` wayNames dflags
797 = StgDoMassageForProfiling : todo1
801 -- -----------------------------------------------------------------------------
805 allFlags = map ('-':) $
806 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
807 map ("fno-"++) flags ++
809 where ok (PrefixPred _ _) = False
811 flags = map fst fFlags
813 dynamic_flags :: [(String, OptKind DynP)]
815 ( "n" , NoArg (setDynFlag Opt_DryRun) )
816 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
817 , ( "F" , NoArg (setDynFlag Opt_Pp))
818 , ( "#include" , HasArg (addCmdlineHCInclude) )
819 , ( "v" , OptIntSuffix setVerbosity )
820 ------- Specific phases --------------------------------------------
821 , ( "pgmL" , HasArg (upd . setPgmL) )
822 , ( "pgmP" , HasArg (upd . setPgmP) )
823 , ( "pgmF" , HasArg (upd . setPgmF) )
824 , ( "pgmc" , HasArg (upd . setPgmc) )
825 , ( "pgmm" , HasArg (upd . setPgmm) )
826 , ( "pgms" , HasArg (upd . setPgms) )
827 , ( "pgma" , HasArg (upd . setPgma) )
828 , ( "pgml" , HasArg (upd . setPgml) )
829 , ( "pgmdll" , HasArg (upd . setPgmdll) )
831 , ( "optL" , HasArg (upd . addOptL) )
832 , ( "optP" , HasArg (upd . addOptP) )
833 , ( "optF" , HasArg (upd . addOptF) )
834 , ( "optc" , HasArg (upd . addOptc) )
835 , ( "optm" , HasArg (upd . addOptm) )
836 , ( "opta" , HasArg (upd . addOpta) )
837 , ( "optl" , HasArg (upd . addOptl) )
838 , ( "optdll" , HasArg (upd . addOptdll) )
839 , ( "optdep" , HasArg (upd . addOptdep) )
841 , ( "split-objs" , NoArg (if can_split
842 then setDynFlag Opt_SplitObjs
845 -------- Linking ----------------------------------------------------
846 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
847 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
848 , ( "-mk-dll" , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
850 ------- Libraries ---------------------------------------------------
851 , ( "L" , Prefix addLibraryPath )
852 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
855 ------- Frameworks --------------------------------------------------
856 -- -framework-path should really be -F ...
857 , ( "framework-path" , HasArg addFrameworkPath )
858 , ( "framework" , HasArg (upd . addCmdlineFramework) )
860 ------- Output Redirection ------------------------------------------
861 , ( "odir" , HasArg (upd . setObjectDir . Just))
862 , ( "o" , SepArg (upd . setOutputFile . Just))
863 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
864 , ( "osuf" , HasArg (upd . setObjectSuf))
865 , ( "hcsuf" , HasArg (upd . setHcSuf))
866 , ( "hisuf" , HasArg (upd . setHiSuf))
867 , ( "hidir" , HasArg (upd . setHiDir . Just))
868 , ( "tmpdir" , HasArg (upd . setTmpDir))
869 , ( "stubdir" , HasArg (upd . setStubDir . Just))
871 ------- Keeping temporary files -------------------------------------
872 , ( "keep-hc-file" , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
873 , ( "keep-s-file" , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
874 , ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
875 , ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
877 ------- Miscellaneous ----------------------------------------------
878 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
879 , ( "main-is" , SepArg setMainIs )
880 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
881 , ( "hpcdir" , SepArg setOptHpcDir )
883 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
884 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
885 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
887 ------- Packages ----------------------------------------------------
888 , ( "package-conf" , HasArg extraPkgConf_ )
889 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
890 , ( "package-name" , HasArg (upd . setPackageName) )
891 , ( "package" , HasArg exposePackage )
892 , ( "hide-package" , HasArg hidePackage )
893 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
894 , ( "ignore-package" , HasArg ignorePackage )
895 , ( "syslib" , HasArg exposePackage ) -- for compatibility
897 ------ HsCpp opts ---------------------------------------------------
898 , ( "D", AnySuffix (upd . addOptP) )
899 , ( "U", AnySuffix (upd . addOptP) )
901 ------- Include/Import Paths ----------------------------------------
902 , ( "I" , Prefix addIncludePath)
903 , ( "i" , OptPrefix addImportPath )
905 ------ Debugging ----------------------------------------------------
906 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
908 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
909 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
910 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
911 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
912 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
913 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
914 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
915 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
916 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
917 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
918 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
919 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
920 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
921 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
922 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
923 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
924 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
925 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
926 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
927 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
928 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
929 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
930 , ( "ddump-rn-trace", NoArg (setDynFlag Opt_D_dump_rn_trace))
931 , ( "ddump-if-trace", NoArg (setDynFlag Opt_D_dump_if_trace))
932 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
933 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
934 , ( "ddump-rn-stats", NoArg (setDynFlag Opt_D_dump_rn_stats))
935 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
936 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
937 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
938 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
939 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
940 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
941 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
942 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
943 , ( "ddump-minimal-imports", NoArg (setDynFlag Opt_D_dump_minimal_imports))
944 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
945 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
947 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
948 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
949 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
950 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
951 setVerbosity (Just 2)) )
952 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
954 ------ Machine dependant (-m<blah>) stuff ---------------------------
956 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
957 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
958 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
960 ------ Warning opts -------------------------------------------------
961 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
962 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
963 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
964 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
965 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
967 ------ Optimisation flags ------------------------------------------
968 , ( "O" , NoArg (upd (setOptLevel 1)))
969 , ( "Onot" , NoArg (upd (setOptLevel 0)))
970 , ( "O" , PrefixPred (all isDigit)
971 (\f -> upd (setOptLevel (read f))))
973 , ( "fmax-simplifier-iterations",
974 PrefixPred (all isDigit)
976 dfs{ maxSimplIterations = read n })) )
979 SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
981 ------ Compiler flags -----------------------------------------------
983 , ( "fno-code", NoArg (setTarget HscNothing))
984 , ( "fasm", AnySuffix (\_ -> setTarget HscAsm) )
985 , ( "fvia-c", NoArg (setTarget HscC) )
986 , ( "fvia-C", NoArg (setTarget HscC) )
988 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
989 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
991 , ( "fcontext-stack" , OptIntSuffix $ \mb_n -> upd $ \dfs ->
992 dfs{ ctxtStkDepth = mb_n `orElse` 3 })
994 -- the rest of the -f* and -fno-* flags
995 , ( "fno-", PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
996 , ( "f", PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
999 -- these -f<blah> flags can all be reversed with -fno-<blah>
1002 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1003 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1004 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1005 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1006 ( "warn-missing-fields", Opt_WarnMissingFields ),
1007 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1008 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1009 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1010 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1011 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1012 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1013 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1014 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1015 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1016 ( "warn-deprecations", Opt_WarnDeprecations ),
1017 ( "warn-orphans", Opt_WarnOrphans ),
1018 ( "fi", Opt_FFI ), -- support `-ffi'...
1019 ( "ffi", Opt_FFI ), -- ...and also `-fffi'
1020 ( "arrows", Opt_Arrows ), -- arrow syntax
1021 ( "parr", Opt_PArr ),
1023 ( "implicit-prelude", Opt_ImplicitPrelude ),
1024 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1025 ( "bang-patterns", Opt_BangPatterns ),
1026 ( "indexed-types", Opt_IndexedTypes ),
1027 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1028 ( "mono-pat-binds", Opt_MonoPatBinds ),
1029 ( "extended-default-rules", Opt_ExtendedDefaultRules ),
1030 ( "implicit-params", Opt_ImplicitParams ),
1031 ( "allow-overlapping-instances", Opt_AllowOverlappingInstances ),
1032 ( "allow-undecidable-instances", Opt_AllowUndecidableInstances ),
1033 ( "allow-incoherent-instances", Opt_AllowIncoherentInstances ),
1034 ( "generics", Opt_Generics ),
1035 ( "strictness", Opt_Strictness ),
1036 ( "full-laziness", Opt_FullLaziness ),
1038 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1039 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1040 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1041 ( "ignore-asserts", Opt_IgnoreAsserts ),
1042 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1043 ( "do-eta-reduction", Opt_DoEtaReduction ),
1044 ( "case-merge", Opt_CaseMerge ),
1045 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1046 ( "dicts-cheap", Opt_DictsCheap ),
1047 ( "excess-precision", Opt_ExcessPrecision ),
1048 ( "asm-mangling", Opt_DoAsmMangling ),
1049 ( "print-bind-result", Opt_PrintBindResult ),
1050 ( "force-recomp", Opt_ForceRecomp )
1054 glasgowExtsFlags = [
1058 Opt_ScopedTypeVariables,
1061 isFFlag f = f `elem` (map fst fFlags)
1062 getFFlag f = fromJust (lookup f fFlags)
1064 -- -----------------------------------------------------------------------------
1065 -- Parsing the dynamic flags.
1067 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1068 parseDynamicFlags dflags args = do
1069 let ((leftover,errs),dflags')
1070 = runCmdLine (processArgs dynamic_flags args) dflags
1071 when (not (null errs)) $ do
1072 throwDyn (UsageError (unlines errs))
1073 return (dflags', leftover)
1076 type DynP = CmdLineP DynFlags
1078 upd :: (DynFlags -> DynFlags) -> DynP ()
1080 dfs <- getCmdLineState
1081 putCmdLineState $! (f dfs)
1083 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1084 setDynFlag f = upd (\dfs -> dopt_set dfs f)
1085 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1087 setDumpFlag :: DynFlag -> OptKind DynP
1088 setDumpFlag dump_flag
1089 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1090 -- Whenver we -ddump, switch off the recompilation checker,
1091 -- else you don't see the dump!
1093 setVerbosity :: Maybe Int -> DynP ()
1094 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1096 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1098 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1101 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1103 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1105 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1108 | Nothing <- unpackPackageId pid
1109 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1111 = \s -> s{ thisPackage = pid }
1113 pid = stringToPackageId p
1115 -- we can only switch between HscC, and HscAsmm with dynamic flags
1116 -- (-fvia-C, -fasm, -filx respectively).
1117 setTarget l = upd (\dfs -> case hscTarget dfs of
1118 HscC -> dfs{ hscTarget = l }
1119 HscAsm -> dfs{ hscTarget = l }
1122 setOptLevel :: Int -> DynFlags -> DynFlags
1123 setOptLevel n dflags
1124 | hscTarget dflags == HscInterpreted && n > 0
1126 -- not in IO any more, oh well:
1127 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1129 = updOptLevel n dflags
1132 setMainIs :: String -> DynP ()
1134 | not (null main_fn) -- The arg looked like "Foo.baz"
1135 = upd $ \d -> d{ mainFunIs = Just main_fn,
1136 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1138 | isUpper (head main_mod) -- The arg looked like "Foo"
1139 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1141 | otherwise -- The arg looked like "baz"
1142 = upd $ \d -> d{ mainFunIs = Just main_mod }
1144 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1146 -----------------------------------------------------------------------------
1147 -- Paths & Libraries
1149 -- -i on its own deletes the import paths
1150 addImportPath "" = upd (\s -> s{importPaths = []})
1151 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1155 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1158 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1160 addFrameworkPath p =
1161 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1163 split_marker = ':' -- not configurable (ToDo)
1165 splitPathList :: String -> [String]
1166 splitPathList s = filter notNull (splitUp s)
1167 -- empty paths are ignored: there might be a trailing
1168 -- ':' in the initial list, for example. Empty paths can
1169 -- cause confusion when they are translated into -I options
1170 -- for passing to gcc.
1172 #ifndef mingw32_TARGET_OS
1173 splitUp xs = split split_marker xs
1175 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1177 -- That is, if "foo:bar:baz" is used, this interpreted as
1178 -- consisting of three entries, 'foo', 'bar', 'baz'.
1179 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1180 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1182 -- Notice that no attempt is made to fully replace the 'standard'
1183 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1184 -- that this will cause too much breakage for users & ':' will
1185 -- work fine even with DOS paths, if you're not insisting on being silly.
1188 splitUp (x:':':div:xs) | div `elem` dir_markers
1189 = ((x:':':div:p): splitUp rs)
1191 (p,rs) = findNextPath xs
1192 -- we used to check for existence of the path here, but that
1193 -- required the IO monad to be threaded through the command-line
1194 -- parser which is quite inconvenient. The
1195 splitUp xs = cons p (splitUp rs)
1197 (p,rs) = findNextPath xs
1202 -- will be called either when we've consumed nought or the
1203 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1204 -- finding the next split marker.
1206 case break (`elem` split_markers) xs of
1207 (p, d:ds) -> (p, ds)
1210 split_markers :: [Char]
1211 split_markers = [':', ';']
1213 dir_markers :: [Char]
1214 dir_markers = ['/', '\\']
1217 -- -----------------------------------------------------------------------------
1218 -- tmpDir, where we store temporary files.
1220 setTmpDir :: FilePath -> DynFlags -> DynFlags
1221 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1223 #if !defined(mingw32_HOST_OS)
1224 canonicalise p = normalisePath p
1226 -- Canonicalisation of temp path under win32 is a bit more
1227 -- involved: (a) strip trailing slash,
1228 -- (b) normalise slashes
1229 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1231 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1233 -- if we're operating under cygwin, and TMP/TEMP is of
1234 -- the form "/cygdrive/drive/path", translate this to
1235 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1236 -- understand /cygdrive paths.)
1238 | "/cygdrive/" `isPrefixOf` path =
1239 case drop (length "/cygdrive/") path of
1240 drive:xs@('/':_) -> drive:':':xs
1244 -- strip the trailing backslash (awful, but we only do this once).
1245 removeTrailingSlash path =
1252 -----------------------------------------------------------------------------
1255 setOptHpcDir :: String -> DynP ()
1256 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1258 -----------------------------------------------------------------------------
1259 -- Via-C compilation stuff
1261 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1262 [String]) -- for registerised HC compilations
1263 machdepCCOpts dflags
1264 #if alpha_TARGET_ARCH
1266 #ifdef HAVE_THREADED_RTS_SUPPORT
1270 -- For now, to suppress the gcc warning "call-clobbered
1271 -- register used for global register variable", we simply
1272 -- disable all warnings altogether using the -w flag. Oh well.
1274 #elif hppa_TARGET_ARCH
1275 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1276 -- (very nice, but too bad the HP /usr/include files don't agree.)
1277 = ( ["-D_HPUX_SOURCE"], [] )
1279 #elif m68k_TARGET_ARCH
1280 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1281 -- popping of args to routines to be explicit; if we let things
1282 -- be deferred 'til after an STGJUMP, imminent death is certain!
1284 -- -fomit-frame-pointer : *don't*
1285 -- It's better to have a6 completely tied up being a frame pointer
1286 -- rather than let GCC pick random things to do with it.
1287 -- (If we want to steal a6, then we would try to do things
1288 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1289 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1291 #elif i386_TARGET_ARCH
1292 -- -fno-defer-pop : basically the same game as for m68k
1294 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1295 -- the fp (%ebp) for our register maps.
1296 = let n_regs = stolen_x86_regs dflags
1299 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1300 -- , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else ""
1303 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1304 -- Some gccs are configured with
1305 -- -momit-leaf-frame-pointer on by default, and it
1306 -- apparently takes precedence over
1307 -- -fomit-frame-pointer, so we disable it first here.
1308 "-mno-omit-leaf-frame-pointer",
1310 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1311 "-fno-unit-at-a-time",
1312 -- unit-at-a-time doesn't do us any good, and screws
1313 -- up -split-objs by moving the split markers around.
1314 -- It's only turned on with -O2, but put it here just
1315 -- in case someone uses -optc-O2.
1317 "-fomit-frame-pointer",
1318 -- we want -fno-builtin, because when gcc inlines
1319 -- built-in functions like memcpy() it tends to
1320 -- run out of registers, requiring -monly-n-regs
1322 "-DSTOLEN_X86_REGS="++show n_regs ]
1325 #elif ia64_TARGET_ARCH
1326 = ( [], ["-fomit-frame-pointer", "-G0"] )
1328 #elif x86_64_TARGET_ARCH
1329 = ( [], ["-fomit-frame-pointer",
1330 "-fno-asynchronous-unwind-tables",
1331 -- the unwind tables are unnecessary for HC code,
1332 -- and get in the way of -split-objs. Another option
1333 -- would be to throw them away in the mangler, but this
1335 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1336 "-fno-unit-at-a-time",
1337 -- unit-at-a-time doesn't do us any good, and screws
1338 -- up -split-objs by moving the split markers around.
1339 -- It's only turned on with -O2, but put it here just
1340 -- in case someone uses -optc-O2.
1343 -- calling builtins like strlen() using the FFI can
1344 -- cause gcc to run out of regs, so use the external
1348 #elif sparc_TARGET_ARCH
1350 -- For now, to suppress the gcc warning "call-clobbered
1351 -- register used for global register variable", we simply
1352 -- disable all warnings altogether using the -w flag. Oh well.
1354 #elif powerpc_apple_darwin_TARGET
1356 -- Disable Apple's precompiling preprocessor. It's a great thing
1357 -- for "normal" programs, but it doesn't support register variable
1359 = ( [], ["-no-cpp-precomp"] )
1364 picCCOpts :: DynFlags -> [String]
1366 #if darwin_TARGET_OS
1367 -- Apple prefers to do things the other way round.
1368 -- PIC is on by default.
1369 -- -mdynamic-no-pic:
1370 -- Turn off PIC code generation.
1372 -- Don't generate "common" symbols - these are unwanted
1373 -- in dynamic libraries.
1378 = ["-mdynamic-no-pic"]
1379 #elif mingw32_TARGET_OS
1380 -- no -fPIC for Windows
1389 -- -----------------------------------------------------------------------------
1394 #if defined(i386_TARGET_ARCH) \
1395 || defined(x86_64_TARGET_ARCH) \
1396 || defined(alpha_TARGET_ARCH) \
1397 || defined(hppa_TARGET_ARCH) \
1398 || defined(m68k_TARGET_ARCH) \
1399 || defined(mips_TARGET_ARCH) \
1400 || defined(powerpc_TARGET_ARCH) \
1401 || defined(rs6000_TARGET_ARCH) \
1402 || defined(sparc_TARGET_ARCH)