2 {-# OPTIONS -fno-warn-missing-fields #-}
4 -- The above warning supression flag is a temporary kludge.
5 -- While working on this module you are encouraged to remove it and fix
6 -- any warnings in the module. See
7 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
10 -----------------------------------------------------------------------------
14 -- Most flags are dynamic flags, which means they can change from
15 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
16 -- multi-session GHC each session can be using different dynamic
17 -- flags. Dynamic flags can also be set at the prompt in GHCi.
19 -- (c) The University of Glasgow 2005
21 -----------------------------------------------------------------------------
27 HscTarget(..), isObjectTarget, defaultObjectTarget,
28 GhcMode(..), isOneShot,
29 GhcLink(..), isNoLink,
34 -- Configuration of the core-to-core and stg-to-stg phases
38 SimplifierMode(..), FloatOutSwitches(..),
39 getCoreToDo, getStgToDo,
41 -- Manipulating DynFlags
42 defaultDynFlags, -- DynFlags
43 initDynFlags, -- DynFlags -> IO DynFlags
45 dopt, -- DynFlag -> DynFlags -> Bool
46 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
47 getOpts, -- (DynFlags -> [a]) -> IO [a]
58 machdepCCOpts, picCCOpts,
63 #include "HsVersions.h"
67 import PrelNames ( mAIN )
68 #ifdef i386_TARGET_ARCH
69 import StaticFlags ( opt_Static )
71 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
73 import {-# SOURCE #-} Packages (PackageState)
74 import DriverPhases ( Phase(..), phaseInputExt )
77 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
78 import Panic ( panic, GhcException(..) )
79 import UniqFM ( UniqFM )
81 import Maybes ( orElse, fromJust )
82 import SrcLoc ( SrcSpan )
84 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
86 import Data.IORef ( readIORef )
87 import Control.Exception ( throwDyn )
88 import Control.Monad ( when )
89 #ifdef mingw32_TARGET_OS
90 import Data.List ( isPrefixOf )
96 import System.IO ( hPutStrLn, stderr )
98 -- -----------------------------------------------------------------------------
106 | Opt_D_dump_cmmz_pretty
110 | Opt_D_dump_asm_native
111 | Opt_D_dump_asm_liveness
112 | Opt_D_dump_asm_coalesce
113 | Opt_D_dump_asm_regalloc
114 | Opt_D_dump_asm_regalloc_stages
115 | Opt_D_dump_asm_conflicts
116 | Opt_D_dump_asm_stats
122 | Opt_D_dump_inlinings
123 | Opt_D_dump_rule_firings
124 | Opt_D_dump_occur_anal
128 | Opt_D_dump_simpl_iterations
137 | Opt_D_dump_worker_wrapper
138 | Opt_D_dump_rn_trace
139 | Opt_D_dump_rn_stats
141 | Opt_D_dump_simpl_stats
142 | Opt_D_dump_tc_trace
143 | Opt_D_dump_if_trace
149 | Opt_D_verbose_core2core
150 | Opt_D_verbose_stg2stg
152 | Opt_D_dump_hi_diffs
153 | Opt_D_dump_minimal_imports
154 | Opt_D_dump_mod_cycles
155 | Opt_D_dump_view_pattern_commoning
156 | Opt_D_faststring_stats
157 | Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
163 | Opt_WarnIsError -- -Werror; makes warnings fatal
164 | Opt_WarnDuplicateExports
166 | Opt_WarnImplicitPrelude
167 | Opt_WarnIncompletePatterns
168 | Opt_WarnIncompletePatternsRecUpd
169 | Opt_WarnMissingFields
170 | Opt_WarnMissingMethods
171 | Opt_WarnMissingSigs
172 | Opt_WarnNameShadowing
173 | Opt_WarnOverlappingPatterns
174 | Opt_WarnSimplePatterns
175 | Opt_WarnTypeDefaults
176 | Opt_WarnMonomorphism
177 | Opt_WarnUnusedBinds
178 | Opt_WarnUnusedImports
179 | Opt_WarnUnusedMatches
180 | Opt_WarnDeprecations
181 | Opt_WarnDodgyImports
186 | Opt_OverlappingInstances
187 | Opt_UndecidableInstances
188 | Opt_IncoherentInstances
189 | Opt_MonomorphismRestriction
191 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
192 | Opt_ForeignFunctionInterface
193 | Opt_UnliftedFFITypes
194 | Opt_PArr -- Syntactic support for parallel arrays
195 | Opt_Arrows -- Arrow-notation syntax
196 | Opt_TemplateHaskell
199 | Opt_ImplicitPrelude
200 | Opt_ScopedTypeVariables
204 | Opt_OverloadedStrings
205 | Opt_DisambiguateRecordFields
206 | Opt_RecordWildCards
211 | Opt_StandaloneDeriving
212 | Opt_DeriveDataTypeable
213 | Opt_TypeSynonymInstances
214 | Opt_FlexibleContexts
215 | Opt_FlexibleInstances
216 | Opt_ConstrainedClassMethods
217 | Opt_MultiParamTypeClasses
218 | Opt_FunctionalDependencies
220 | Opt_PolymorphicComponents
221 | Opt_ExistentialQuantification
225 | Opt_PatternSignatures
226 | Opt_ParallelListComp
227 | Opt_GeneralizedNewtypeDeriving
230 | Opt_LiberalTypeSynonyms
235 | Opt_PrintExplicitForalls
243 | Opt_IgnoreInterfacePragmas
244 | Opt_OmitInterfacePragmas
245 | Opt_DoLambdaEtaExpansion
247 | Opt_IgnoreBreakpoints
250 | Opt_UnboxStrictFields
254 | Opt_RegsGraph -- do graph coloring register allocation
255 | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
263 | Opt_ExcessPrecision
264 | Opt_ReadUserPackageConf
268 | Opt_HideAllPackages
269 | Opt_PrintBindResult
273 | Opt_BreakOnException
275 | Opt_PrintEvldWithShow
279 | Opt_ConvertToZipCfgAndBack
290 data DynFlags = DynFlags {
293 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
294 stgToDo :: Maybe [StgToDo], -- similarly
295 hscTarget :: HscTarget,
296 hscOutName :: String, -- name of the output file
297 extCoreName :: String, -- name of the .core output file
298 verbosity :: Int, -- verbosity level
299 optLevel :: Int, -- optimisation level
300 maxSimplIterations :: Int, -- max simplifier iterations
301 ruleCheck :: Maybe String,
303 specThreshold :: Int, -- Threshold for function specialisation
305 stolen_x86_regs :: Int,
306 cmdlineHcIncludes :: [String], -- -#includes
307 importPaths :: [FilePath],
309 mainFunIs :: Maybe String,
310 ctxtStkDepth :: Int, -- Typechecker context stack depth
312 thisPackage :: PackageId,
315 wayNames :: [WayName], -- way flags from the cmd line
316 buildTag :: String, -- the global "way" (eg. "p" for prof)
317 rtsBuildTag :: String, -- the RTS "way"
320 objectDir :: Maybe String,
321 hiDir :: Maybe String,
322 stubDir :: Maybe String,
328 outputFile :: Maybe String,
329 outputHi :: Maybe String,
331 -- | This is set by DriverPipeline.runPipeline based on where
332 -- its output is going.
333 dumpPrefix :: Maybe FilePath,
335 -- | Override the dumpPrefix set by runPipeline.
336 -- Set by -ddump-file-prefix
337 dumpPrefixForce :: Maybe FilePath,
339 includePaths :: [String],
340 libraryPaths :: [String],
341 frameworkPaths :: [String], -- used on darwin only
342 cmdlineFrameworks :: [String], -- ditto
343 tmpDir :: String, -- no trailing '/'
345 ghcUsagePath :: FilePath, -- Filled in by SysTools
346 ghciUsagePath :: FilePath, -- ditto
348 hpcDir :: String, -- ^ path to store the .mix files
350 -- options for particular phases
359 opt_windres :: [String],
361 -- commands for particular phases
363 pgm_P :: (String,[Option]),
365 pgm_c :: (String,[Option]),
366 pgm_m :: (String,[Option]),
367 pgm_s :: (String,[Option]),
368 pgm_a :: (String,[Option]),
369 pgm_l :: (String,[Option]),
370 pgm_dll :: (String,[Option]),
372 pgm_sysman :: String,
373 pgm_windres :: String,
376 extraPkgConfs :: [FilePath],
377 topDir :: FilePath, -- filled in by SysTools
378 systemPackageConfig :: FilePath, -- ditto
379 -- The -package-conf flags given on the command line, in the order
382 packageFlags :: [PackageFlag],
383 -- The -package and -hide-package flags from the command-line
386 -- NB. do not modify this field, it is calculated by
387 -- Packages.initPackages and Packages.updatePackages.
388 pkgDatabase :: Maybe (UniqFM PackageConfig),
389 pkgState :: PackageState,
395 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO (),
397 haddockOptions :: Maybe String
408 -- | will this target result in an object file on the disk?
409 isObjectTarget :: HscTarget -> Bool
410 isObjectTarget HscC = True
411 isObjectTarget HscAsm = True
412 isObjectTarget _ = False
414 -- | The 'GhcMode' tells us whether we're doing multi-module
415 -- compilation (controlled via the "GHC" API) or one-shot
416 -- (single-module) compilation. This makes a difference primarily to
417 -- the "Finder": in one-shot mode we look for interface files for
418 -- imported modules, but in multi-module mode we look for source files
419 -- in order to check whether they need to be recompiled.
421 = CompManager -- ^ --make, GHCi, etc.
422 | OneShot -- ^ ghc -c Foo.hs
423 | MkDepend -- ^ ghc -M, see Finder for why we need this
426 isOneShot :: GhcMode -> Bool
427 isOneShot OneShot = True
428 isOneShot _other = False
430 -- | What kind of linking to do.
431 data GhcLink -- What to do in the link step, if there is one
432 = NoLink -- Don't link at all
433 | LinkBinary -- Link object code into a binary
434 | LinkInMemory -- Use the in-memory dynamic linker
435 | LinkDynLib -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
438 isNoLink :: GhcLink -> Bool
439 isNoLink NoLink = True
440 isNoLink other = False
443 = ExposePackage String
445 | IgnorePackage String
448 defaultHscTarget = defaultObjectTarget
450 -- | the 'HscTarget' value corresponding to the default way to create
451 -- object files on the current platform.
453 | cGhcWithNativeCodeGen == "YES" = HscAsm
456 initDynFlags dflags = do
457 -- someday these will be dynamic flags
458 ways <- readIORef v_Ways
459 build_tag <- readIORef v_Build_tag
460 rts_build_tag <- readIORef v_RTS_Build_tag
463 buildTag = build_tag,
464 rtsBuildTag = rts_build_tag
469 ghcMode = CompManager,
470 ghcLink = LinkBinary,
473 hscTarget = defaultHscTarget,
478 maxSimplIterations = 4,
482 cmdlineHcIncludes = [],
486 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
488 thisPackage = mainPackageId,
494 objectSuf = phaseInputExt StopLn,
495 hcSuf = phaseInputExt HCc,
498 outputFile = Nothing,
500 dumpPrefix = Nothing,
501 dumpPrefixForce = Nothing,
505 cmdlineFrameworks = [],
506 tmpDir = cDEFAULT_TMPDIR,
524 pkgDatabase = Nothing,
525 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
526 haddockOptions = Nothing,
528 Opt_ReadUserPackageConf,
530 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
531 -- behaviour the default, to see if anyone notices
535 Opt_MonomorphismRestriction,
543 Opt_PrintBindResult ]
544 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
545 -- The default -O0 options
548 log_action = \severity srcSpan style msg ->
550 SevInfo -> hPutStrLn stderr (show (msg style))
551 SevFatal -> hPutStrLn stderr (show (msg style))
552 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
558 0 | print errors & warnings only
559 1 | minimal verbosity: print "compiling M ... done." for each module.
560 2 | equivalent to -dshow-passes
561 3 | equivalent to existing "ghc -v"
562 4 | "ghc -v -ddump-most"
563 5 | "ghc -v -ddump-all"
566 dopt :: DynFlag -> DynFlags -> Bool
567 dopt f dflags = f `elem` (flags dflags)
569 dopt_set :: DynFlags -> DynFlag -> DynFlags
570 dopt_set dfs f = dfs{ flags = f : flags dfs }
572 dopt_unset :: DynFlags -> DynFlag -> DynFlags
573 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
575 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
576 getOpts dflags opts = reverse (opts dflags)
577 -- We add to the options from the front, so we need to reverse the list
579 getVerbFlag :: DynFlags -> String
581 | verbosity dflags >= 3 = "-v"
584 setObjectDir f d = d{ objectDir = Just f}
585 setHiDir f d = d{ hiDir = Just f}
586 setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
587 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
588 -- #included from the .hc file when compiling with -fvia-C.
590 setObjectSuf f d = d{ objectSuf = f}
591 setHiSuf f d = d{ hiSuf = f}
592 setHcSuf f d = d{ hcSuf = f}
594 setOutputFile f d = d{ outputFile = f}
595 setOutputHi f d = d{ outputHi = f}
597 setDumpPrefixForce f d = d { dumpPrefixForce = f}
599 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
600 -- Config.hs should really use Option.
601 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
603 setPgmL f d = d{ pgm_L = f}
604 setPgmF f d = d{ pgm_F = f}
605 setPgmc f d = d{ pgm_c = (f,[])}
606 setPgmm f d = d{ pgm_m = (f,[])}
607 setPgms f d = d{ pgm_s = (f,[])}
608 setPgma f d = d{ pgm_a = (f,[])}
609 setPgml f d = d{ pgm_l = (f,[])}
610 setPgmdll f d = d{ pgm_dll = (f,[])}
611 setPgmwindres f d = d{ pgm_windres = f}
613 addOptL f d = d{ opt_L = f : opt_L d}
614 addOptP f d = d{ opt_P = f : opt_P d}
615 addOptF f d = d{ opt_F = f : opt_F d}
616 addOptc f d = d{ opt_c = f : opt_c d}
617 addOptm f d = d{ opt_m = f : opt_m d}
618 addOpta f d = d{ opt_a = f : opt_a d}
619 addOptl f d = d{ opt_l = f : opt_l d}
620 addOptdep f d = d{ opt_dep = f : opt_dep d}
621 addOptwindres f d = d{ opt_windres = f : opt_windres d}
623 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
625 addHaddockOpts f d = d{ haddockOptions = Just f}
627 -- -----------------------------------------------------------------------------
628 -- Command-line options
630 -- When invoking external tools as part of the compilation pipeline, we
631 -- pass these a sequence of options on the command-line. Rather than
632 -- just using a list of Strings, we use a type that allows us to distinguish
633 -- between filepaths and 'other stuff'. [The reason being, of course, that
634 -- this type gives us a handle on transforming filenames, and filenames only,
635 -- to whatever format they're expected to be on a particular platform.]
638 = FileOption -- an entry that _contains_ filename(s) / filepaths.
639 String -- a non-filepath prefix that shouldn't be
640 -- transformed (e.g., "/out=")
641 String -- the filepath/filename portion
644 -----------------------------------------------------------------------------
645 -- Setting the optimisation level
647 updOptLevel :: Int -> DynFlags -> DynFlags
648 -- Set dynflags appropriate to the optimisation level
650 = dfs2{ optLevel = final_n }
652 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
653 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
654 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
656 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
657 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
659 optLevelFlags :: [([Int], DynFlag)]
661 = [ ([0], Opt_IgnoreInterfacePragmas)
662 , ([0], Opt_OmitInterfacePragmas)
664 , ([1,2], Opt_IgnoreAsserts)
665 , ([1,2], Opt_RewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
667 , ([1,2], Opt_DoEtaReduction)
668 , ([1,2], Opt_CaseMerge)
669 , ([1,2], Opt_Strictness)
671 , ([1,2], Opt_FullLaziness)
673 , ([2], Opt_LiberateCase)
674 , ([2], Opt_SpecConstr)
676 , ([0,1,2], Opt_DoLambdaEtaExpansion)
677 -- This one is important for a tiresome reason:
678 -- we want to make sure that the bindings for data
679 -- constructors are eta-expanded. This is probably
680 -- a good thing anyway, but it seems fragile.
683 -- -----------------------------------------------------------------------------
684 -- Standard sets of warning options
687 = [ Opt_WarnDeprecations,
688 Opt_WarnOverlappingPatterns,
689 Opt_WarnMissingFields,
690 Opt_WarnMissingMethods,
691 Opt_WarnDuplicateExports
695 = standardWarnings ++
696 [ Opt_WarnUnusedBinds,
697 Opt_WarnUnusedMatches,
698 Opt_WarnUnusedImports,
699 Opt_WarnIncompletePatterns,
705 [ Opt_WarnTypeDefaults,
706 Opt_WarnNameShadowing,
712 -- minuswRemovesOpts should be every warning option
715 [Opt_WarnImplicitPrelude,
716 Opt_WarnIncompletePatternsRecUpd,
717 Opt_WarnSimplePatterns,
718 Opt_WarnMonomorphism,
722 -- -----------------------------------------------------------------------------
723 -- CoreToDo: abstraction of core-to-core passes to run.
725 data CoreToDo -- These are diff core-to-core passes,
726 -- which may be invoked in any order,
727 -- as many times as you like.
729 = CoreDoSimplify -- The core-to-core simplifier.
732 -- Each run of the simplifier can take a different
733 -- set of simplifier-specific flags.
735 | CoreDoFloatOutwards FloatOutSwitches
740 | CoreDoWorkerWrapper
743 | CoreDoOldStrictness
746 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
747 -- matching this string
748 | CoreDoVectorisation
749 | CoreDoNothing -- Useful when building up
750 | CoreDoPasses [CoreToDo] -- lists of these things
752 data SimplifierMode -- See comments in SimplMonad
756 data SimplifierSwitch
757 = MaxSimplifierIterations Int
760 data FloatOutSwitches
761 = FloatOutSw Bool -- True <=> float lambdas to top level
762 Bool -- True <=> float constants to top level,
763 -- even if they do not escape a lambda
766 -- The core-to-core pass ordering is derived from the DynFlags:
767 runWhen :: Bool -> CoreToDo -> CoreToDo
768 runWhen True do_this = do_this
769 runWhen False do_this = CoreDoNothing
771 getCoreToDo :: DynFlags -> [CoreToDo]
773 | Just todo <- coreToDo dflags = todo -- set explicitly by user
774 | otherwise = core_todo
776 opt_level = optLevel dflags
777 max_iter = maxSimplIterations dflags
778 strictness = dopt Opt_Strictness dflags
779 full_laziness = dopt Opt_FullLaziness dflags
780 cse = dopt Opt_CSE dflags
781 spec_constr = dopt Opt_SpecConstr dflags
782 liberate_case = dopt Opt_LiberateCase dflags
783 rule_check = ruleCheck dflags
784 vectorisation = dopt Opt_Vectorise dflags
787 if opt_level == 0 then
789 CoreDoSimplify (SimplPhase 0) [
790 MaxSimplifierIterations max_iter
793 else {- opt_level >= 1 -} [
795 -- initial simplify: mk specialiser happy: minimum effort please
796 CoreDoSimplify SimplGently [
798 -- Don't inline anything till full laziness has bitten
799 -- In particular, inlining wrappers inhibits floating
800 -- e.g. ...(case f x of ...)...
801 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
802 -- ==> ...(case x of I# x# -> case fw x# of ...)...
803 -- and now the redex (f x) isn't floatable any more
804 -- Similarly, don't apply any rules until after full
805 -- laziness. Notably, list fusion can prevent floating.
807 NoCaseOfCase, -- Don't do case-of-case transformations.
808 -- This makes full laziness work better
809 MaxSimplifierIterations max_iter
813 -- We run vectorisation here for now, but we might also try to run
815 runWhen vectorisation (CoreDoPasses [
817 CoreDoSimplify SimplGently
819 MaxSimplifierIterations max_iter]]),
821 -- Specialisation is best done before full laziness
822 -- so that overloaded functions have all their dictionary lambdas manifest
825 runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
829 CoreDoSimplify (SimplPhase 2) [
830 -- Want to run with inline phase 2 after the specialiser to give
831 -- maximum chance for fusion to work before we inline build/augment
832 -- in phase 1. This made a difference in 'ansi' where an
833 -- overloaded function wasn't inlined till too late.
834 MaxSimplifierIterations max_iter
836 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
838 CoreDoSimplify (SimplPhase 1) [
839 -- Need inline-phase2 here so that build/augment get
840 -- inlined. I found that spectral/hartel/genfft lost some useful
841 -- strictness in the function sumcode' if augment is not inlined
842 -- before strictness analysis runs
843 MaxSimplifierIterations max_iter
845 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
847 CoreDoSimplify (SimplPhase 0) [
848 -- Phase 0: allow all Ids to be inlined now
849 -- This gets foldr inlined before strictness analysis
851 MaxSimplifierIterations 3
852 -- At least 3 iterations because otherwise we land up with
853 -- huge dead expressions because of an infelicity in the
855 -- let k = BIG in foldr k z xs
856 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
857 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
861 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
863 #ifdef OLD_STRICTNESS
866 runWhen strictness (CoreDoPasses [
870 CoreDoSimplify (SimplPhase 0) [
871 MaxSimplifierIterations max_iter
874 runWhen full_laziness
875 (CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
876 True)), -- Float constants
877 -- nofib/spectral/hartel/wang doubles in speed if you
878 -- do full laziness late in the day. It only happens
879 -- after fusion and other stuff, so the early pass doesn't
880 -- catch it. For the record, the redex is
881 -- f_el22 (f_el21 r_midblock)
885 -- We want CSE to follow the final full-laziness pass, because it may
886 -- succeed in commoning up things floated out by full laziness.
887 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
891 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
893 -- Case-liberation for -O2. This should be after
894 -- strictness analysis and the simplification which follows it.
895 runWhen liberate_case (CoreDoPasses [
897 CoreDoSimplify (SimplPhase 0) [
898 MaxSimplifierIterations max_iter
899 ] ]), -- Run the simplifier after LiberateCase to vastly
900 -- reduce the possiblility of shadowing
901 -- Reason: see Note [Shadowing] in SpecConstr.lhs
903 runWhen spec_constr CoreDoSpecConstr,
905 -- Final clean-up simplification:
906 CoreDoSimplify (SimplPhase 0) [
907 MaxSimplifierIterations max_iter
911 -- -----------------------------------------------------------------------------
912 -- StgToDo: abstraction of stg-to-stg passes to run.
915 = StgDoMassageForProfiling -- should be (next to) last
916 -- There's also setStgVarInfo, but its absolute "lastness"
917 -- is so critical that it is hardwired in (no flag).
920 getStgToDo :: DynFlags -> [StgToDo]
922 | Just todo <- stgToDo dflags = todo -- set explicitly by user
925 stg_stats = dopt Opt_StgStats dflags
927 todo1 = if stg_stats then [D_stg_stats] else []
929 todo2 | WayProf `elem` wayNames dflags
930 = StgDoMassageForProfiling : todo1
934 -- -----------------------------------------------------------------------------
938 allFlags = map ('-':) $
939 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
940 map ("fno-"++) flags ++
942 where ok (PrefixPred _ _) = False
944 flags = map fst fFlags
946 dynamic_flags :: [(String, OptKind DynP)]
948 ( "n" , NoArg (setDynFlag Opt_DryRun) )
949 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
950 , ( "F" , NoArg (setDynFlag Opt_Pp))
951 , ( "#include" , HasArg (addCmdlineHCInclude) )
952 , ( "v" , OptIntSuffix setVerbosity )
954 ------- Specific phases --------------------------------------------
955 , ( "pgmL" , HasArg (upd . setPgmL) )
956 , ( "pgmP" , HasArg (upd . setPgmP) )
957 , ( "pgmF" , HasArg (upd . setPgmF) )
958 , ( "pgmc" , HasArg (upd . setPgmc) )
959 , ( "pgmm" , HasArg (upd . setPgmm) )
960 , ( "pgms" , HasArg (upd . setPgms) )
961 , ( "pgma" , HasArg (upd . setPgma) )
962 , ( "pgml" , HasArg (upd . setPgml) )
963 , ( "pgmdll" , HasArg (upd . setPgmdll) )
964 , ( "pgmwindres" , HasArg (upd . setPgmwindres) )
966 , ( "optL" , HasArg (upd . addOptL) )
967 , ( "optP" , HasArg (upd . addOptP) )
968 , ( "optF" , HasArg (upd . addOptF) )
969 , ( "optc" , HasArg (upd . addOptc) )
970 , ( "optm" , HasArg (upd . addOptm) )
971 , ( "opta" , HasArg (upd . addOpta) )
972 , ( "optl" , HasArg (upd . addOptl) )
973 , ( "optdep" , HasArg (upd . addOptdep) )
974 , ( "optwindres" , HasArg (upd . addOptwindres) )
976 , ( "split-objs" , NoArg (if can_split
977 then setDynFlag Opt_SplitObjs
980 -------- Linking ----------------------------------------------------
981 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
982 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
983 , ( "shared" , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
985 ------- Libraries ---------------------------------------------------
986 , ( "L" , Prefix addLibraryPath )
987 , ( "l" , AnySuffix (\s -> do upd (addOptl s)))
989 ------- Frameworks --------------------------------------------------
990 -- -framework-path should really be -F ...
991 , ( "framework-path" , HasArg addFrameworkPath )
992 , ( "framework" , HasArg (upd . addCmdlineFramework) )
994 ------- Output Redirection ------------------------------------------
995 , ( "odir" , HasArg (upd . setObjectDir))
996 , ( "o" , SepArg (upd . setOutputFile . Just))
997 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
998 , ( "osuf" , HasArg (upd . setObjectSuf))
999 , ( "hcsuf" , HasArg (upd . setHcSuf))
1000 , ( "hisuf" , HasArg (upd . setHiSuf))
1001 , ( "hidir" , HasArg (upd . setHiDir))
1002 , ( "tmpdir" , HasArg (upd . setTmpDir))
1003 , ( "stubdir" , HasArg (upd . setStubDir))
1004 , ( "ddump-file-prefix", HasArg (upd . setDumpPrefixForce . Just))
1006 ------- Keeping temporary files -------------------------------------
1007 -- These can be singular (think ghc -c) or plural (think ghc --make)
1008 , ( "keep-hc-file" , NoArg (setDynFlag Opt_KeepHcFiles))
1009 , ( "keep-hc-files" , NoArg (setDynFlag Opt_KeepHcFiles))
1010 , ( "keep-s-file" , NoArg (setDynFlag Opt_KeepSFiles))
1011 , ( "keep-s-files" , NoArg (setDynFlag Opt_KeepSFiles))
1012 , ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
1013 , ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
1014 -- This only makes sense as plural
1015 , ( "keep-tmp-files" , NoArg (setDynFlag Opt_KeepTmpFiles))
1017 ------- Miscellaneous ----------------------------------------------
1018 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
1019 , ( "main-is" , SepArg setMainIs )
1020 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
1021 , ( "haddock-opts" , HasArg (upd . addHaddockOpts))
1022 , ( "hpcdir" , SepArg setOptHpcDir )
1024 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
1025 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
1026 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
1028 ------- Packages ----------------------------------------------------
1029 , ( "package-conf" , HasArg extraPkgConf_ )
1030 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
1031 , ( "package-name" , HasArg (upd . setPackageName) )
1032 , ( "package" , HasArg exposePackage )
1033 , ( "hide-package" , HasArg hidePackage )
1034 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
1035 , ( "ignore-package" , HasArg ignorePackage )
1036 , ( "syslib" , HasArg exposePackage ) -- for compatibility
1038 ------ HsCpp opts ---------------------------------------------------
1039 , ( "D", AnySuffix (upd . addOptP) )
1040 , ( "U", AnySuffix (upd . addOptP) )
1042 ------- Include/Import Paths ----------------------------------------
1043 , ( "I" , Prefix addIncludePath)
1044 , ( "i" , OptPrefix addImportPath )
1046 ------ Debugging ----------------------------------------------------
1047 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
1049 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
1050 , ( "ddump-cmmz", setDumpFlag Opt_D_dump_cmmz)
1051 , ( "ddump-cmmz-pretty", setDumpFlag Opt_D_dump_cmmz_pretty)
1052 , ( "ddump-cps-cmm", setDumpFlag Opt_D_dump_cps_cmm)
1053 , ( "ddump-cvt-cmm", setDumpFlag Opt_D_dump_cvt_cmm)
1054 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
1055 , ( "ddump-asm-native", setDumpFlag Opt_D_dump_asm_native)
1056 , ( "ddump-asm-liveness", setDumpFlag Opt_D_dump_asm_liveness)
1057 , ( "ddump-asm-coalesce", setDumpFlag Opt_D_dump_asm_coalesce)
1058 , ( "ddump-asm-regalloc", setDumpFlag Opt_D_dump_asm_regalloc)
1059 , ( "ddump-asm-conflicts", setDumpFlag Opt_D_dump_asm_conflicts)
1060 , ( "ddump-asm-regalloc-stages",
1061 setDumpFlag Opt_D_dump_asm_regalloc_stages)
1062 , ( "ddump-asm-stats", setDumpFlag Opt_D_dump_asm_stats)
1063 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
1064 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
1065 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
1066 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
1067 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
1068 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
1069 , ( "ddump-rule-firings", setDumpFlag Opt_D_dump_rule_firings)
1070 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
1071 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
1072 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
1073 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
1074 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
1075 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
1076 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
1077 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
1078 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
1079 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
1080 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
1081 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
1082 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
1083 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
1084 , ( "ddump-rn-trace", setDumpFlag Opt_D_dump_rn_trace)
1085 , ( "ddump-if-trace", setDumpFlag Opt_D_dump_if_trace)
1086 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
1087 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
1088 , ( "ddump-rn-stats", setDumpFlag Opt_D_dump_rn_stats)
1089 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
1090 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
1091 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
1092 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
1093 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
1094 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
1095 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
1096 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
1097 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
1098 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
1099 , ( "ddump-mod-cycles", setDumpFlag Opt_D_dump_mod_cycles)
1100 , ( "ddump-view-pattern-commoning", setDumpFlag Opt_D_dump_view_pattern_commoning)
1101 , ( "ddump-to-file", setDumpFlag Opt_DumpToFile)
1102 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
1103 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
1104 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
1105 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
1106 , ( "dasm-lint", NoArg (setDynFlag Opt_DoAsmLinting))
1107 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
1108 setVerbosity (Just 2)) )
1109 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
1111 ------ Machine dependant (-m<blah>) stuff ---------------------------
1113 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1114 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1115 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1117 ------ Warning opts -------------------------------------------------
1118 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
1119 , ( "Werror", NoArg (setDynFlag Opt_WarnIsError) )
1120 , ( "Wwarn" , NoArg (unSetDynFlag Opt_WarnIsError) )
1121 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
1122 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) -- DEPRECATED
1123 , ( "w" , NoArg (mapM_ unSetDynFlag minuswRemovesOpts) )
1125 ------ Optimisation flags ------------------------------------------
1126 , ( "O" , NoArg (upd (setOptLevel 1)))
1127 , ( "Onot" , NoArg (upd (setOptLevel 0))) -- deprecated
1128 , ( "O" , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1129 -- If the number is missing, use 1
1131 , ( "fmax-simplifier-iterations", IntSuffix (\n ->
1132 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1134 -- liberate-case-threshold is an old flag for '-fspec-threshold'
1135 , ( "fspec-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1136 , ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1138 , ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1139 , ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1141 ------ Compiler flags -----------------------------------------------
1143 , ( "fasm", NoArg (setObjTarget HscAsm) )
1144 , ( "fvia-c", NoArg (setObjTarget HscC) )
1145 , ( "fvia-C", NoArg (setObjTarget HscC) )
1147 , ( "fno-code", NoArg (setTarget HscNothing))
1148 , ( "fbyte-code", NoArg (setTarget HscInterpreted) )
1149 , ( "fobject-code", NoArg (setTarget defaultHscTarget) )
1151 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
1152 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1154 -- the rest of the -f* and -fno-* flags
1155 , ( "f", PrefixPred (isFlag fFlags)
1156 (\f -> setDynFlag (getFlag fFlags f)) )
1157 , ( "f", PrefixPred (isPrefFlag "no-" fFlags)
1158 (\f -> unSetDynFlag (getPrefFlag "no-" fFlags f)) )
1160 -- the -X* and -XNo* flags
1161 , ( "X", PrefixPred (isFlag xFlags)
1162 (\f -> setDynFlag (getFlag xFlags f)) )
1163 , ( "X", PrefixPred (isPrefFlag "No" xFlags)
1164 (\f -> unSetDynFlag (getPrefFlag "No" xFlags f)) )
1167 -- these -f<blah> flags can all be reversed with -fno-<blah>
1170 ( "warn-dodgy-imports", Opt_WarnDodgyImports ),
1171 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1172 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1173 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude ),
1174 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1175 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1176 ( "warn-missing-fields", Opt_WarnMissingFields ),
1177 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1178 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1179 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1180 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1181 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1182 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1183 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism ),
1184 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1185 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1186 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1187 ( "warn-deprecations", Opt_WarnDeprecations ),
1188 ( "warn-orphans", Opt_WarnOrphans ),
1189 ( "warn-tabs", Opt_WarnTabs ),
1190 ( "print-explicit-foralls", Opt_PrintExplicitForalls ),
1191 ( "strictness", Opt_Strictness ),
1192 ( "full-laziness", Opt_FullLaziness ),
1193 ( "liberate-case", Opt_LiberateCase ),
1194 ( "spec-constr", Opt_SpecConstr ),
1196 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1197 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1198 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1199 ( "ignore-asserts", Opt_IgnoreAsserts ),
1200 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1201 ( "do-eta-reduction", Opt_DoEtaReduction ),
1202 ( "case-merge", Opt_CaseMerge ),
1203 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1204 ( "dicts-cheap", Opt_DictsCheap ),
1205 ( "excess-precision", Opt_ExcessPrecision ),
1206 ( "asm-mangling", Opt_DoAsmMangling ),
1207 ( "print-bind-result", Opt_PrintBindResult ),
1208 ( "force-recomp", Opt_ForceRecomp ),
1209 ( "hpc-no-auto", Opt_Hpc_No_Auto ),
1210 ( "rewrite-rules", Opt_RewriteRules ),
1211 ( "break-on-exception", Opt_BreakOnException ),
1212 ( "break-on-error", Opt_BreakOnError ),
1213 ( "print-evld-with-show", Opt_PrintEvldWithShow ),
1214 ( "run-cps", Opt_RunCPSZ ),
1215 ( "convert-to-zipper-and-back", Opt_ConvertToZipCfgAndBack),
1216 ( "vectorise", Opt_Vectorise ),
1217 ( "regs-graph", Opt_RegsGraph),
1218 ( "regs-iterative", Opt_RegsIterative),
1219 -- Deprecated in favour of -XTemplateHaskell:
1220 ( "th", Opt_TemplateHaskell ),
1221 -- Deprecated in favour of -XForeignFunctionInterface:
1222 ( "fi", Opt_ForeignFunctionInterface ),
1223 -- Deprecated in favour of -XForeignFunctionInterface:
1224 ( "ffi", Opt_ForeignFunctionInterface ),
1225 -- Deprecated in favour of -XArrows:
1226 ( "arrows", Opt_Arrows ),
1227 -- Deprecated in favour of -XGenerics:
1228 ( "generics", Opt_Generics ),
1229 -- Deprecated in favour of -XImplicitPrelude:
1230 ( "implicit-prelude", Opt_ImplicitPrelude ),
1231 -- Deprecated in favour of -XBangPatterns:
1232 ( "bang-patterns", Opt_BangPatterns ),
1233 -- Deprecated in favour of -XMonomorphismRestriction:
1234 ( "monomorphism-restriction", Opt_MonomorphismRestriction ),
1235 -- Deprecated in favour of -XMonoPatBinds:
1236 ( "mono-pat-binds", Opt_MonoPatBinds ),
1237 -- Deprecated in favour of -XExtendedDefaultRules:
1238 ( "extended-default-rules", Opt_ExtendedDefaultRules ),
1239 -- Deprecated in favour of -XImplicitParams:
1240 ( "implicit-params", Opt_ImplicitParams ),
1241 -- Deprecated in favour of -XScopedTypeVariables:
1242 ( "scoped-type-variables", Opt_ScopedTypeVariables ),
1243 -- Deprecated in favour of -XPArr:
1244 ( "parr", Opt_PArr ),
1245 -- Deprecated in favour of -XOverlappingInstances:
1246 ( "allow-overlapping-instances", Opt_OverlappingInstances ),
1247 -- Deprecated in favour of -XUndecidableInstances:
1248 ( "allow-undecidable-instances", Opt_UndecidableInstances ),
1249 -- Deprecated in favour of -XIncoherentInstances:
1250 ( "allow-incoherent-instances", Opt_IncoherentInstances ),
1251 ( "gen-manifest", Opt_GenManifest ),
1252 ( "embed-manifest", Opt_EmbedManifest )
1255 supportedLanguages :: [String]
1256 supportedLanguages = map fst xFlags
1258 -- These -X<blah> flags can all be reversed with -XNo<blah>
1259 xFlags :: [(String, DynFlag)]
1262 ( "PatternGuards", Opt_PatternGuards ),
1263 ( "UnicodeSyntax", Opt_UnicodeSyntax ),
1264 ( "MagicHash", Opt_MagicHash ),
1265 ( "PolymorphicComponents", Opt_PolymorphicComponents ),
1266 ( "ExistentialQuantification", Opt_ExistentialQuantification ),
1267 ( "KindSignatures", Opt_KindSignatures ),
1268 ( "PatternSignatures", Opt_PatternSignatures ),
1269 ( "EmptyDataDecls", Opt_EmptyDataDecls ),
1270 ( "ParallelListComp", Opt_ParallelListComp ),
1271 ( "ForeignFunctionInterface", Opt_ForeignFunctionInterface ),
1272 ( "UnliftedFFITypes", Opt_UnliftedFFITypes ),
1273 ( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms ),
1274 ( "Rank2Types", Opt_Rank2Types ),
1275 ( "RankNTypes", Opt_RankNTypes ),
1276 ( "TypeOperators", Opt_TypeOperators ),
1277 ( "RecursiveDo", Opt_RecursiveDo ),
1278 ( "Arrows", Opt_Arrows ),
1279 ( "PArr", Opt_PArr ),
1280 ( "TemplateHaskell", Opt_TemplateHaskell ),
1281 ( "Generics", Opt_Generics ),
1283 ( "ImplicitPrelude", Opt_ImplicitPrelude ),
1284 ( "RecordWildCards", Opt_RecordWildCards ),
1285 ( "RecordPuns", Opt_RecordPuns ),
1286 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields ),
1287 ( "OverloadedStrings", Opt_OverloadedStrings ),
1288 ( "GADTs", Opt_GADTs ),
1289 ( "ViewPatterns", Opt_ViewPatterns),
1290 ( "TypeFamilies", Opt_TypeFamilies ),
1291 ( "BangPatterns", Opt_BangPatterns ),
1293 ( "MonomorphismRestriction", Opt_MonomorphismRestriction ),
1294 -- On by default (which is not strictly H98):
1295 ( "MonoPatBinds", Opt_MonoPatBinds ),
1296 ( "RelaxedPolyRec", Opt_RelaxedPolyRec),
1297 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules ),
1298 ( "ImplicitParams", Opt_ImplicitParams ),
1299 ( "ScopedTypeVariables", Opt_ScopedTypeVariables ),
1300 ( "UnboxedTuples", Opt_UnboxedTuples ),
1301 ( "StandaloneDeriving", Opt_StandaloneDeriving ),
1302 ( "DeriveDataTypeable", Opt_DeriveDataTypeable ),
1303 ( "TypeSynonymInstances", Opt_TypeSynonymInstances ),
1304 ( "FlexibleContexts", Opt_FlexibleContexts ),
1305 ( "FlexibleInstances", Opt_FlexibleInstances ),
1306 ( "ConstrainedClassMethods", Opt_ConstrainedClassMethods ),
1307 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses ),
1308 ( "FunctionalDependencies", Opt_FunctionalDependencies ),
1309 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving ),
1310 ( "OverlappingInstances", Opt_OverlappingInstances ),
1311 ( "UndecidableInstances", Opt_UndecidableInstances ),
1312 ( "IncoherentInstances", Opt_IncoherentInstances )
1315 impliedFlags :: [(DynFlag, [DynFlag])]
1317 ( Opt_GADTs, [Opt_RelaxedPolyRec] ) -- We want type-sig variables to be completely rigid for GADTs
1320 glasgowExtsFlags = [
1321 Opt_PrintExplicitForalls
1322 , Opt_ForeignFunctionInterface
1323 , Opt_UnliftedFFITypes
1325 , Opt_ImplicitParams
1326 , Opt_ScopedTypeVariables
1328 , Opt_TypeSynonymInstances
1329 , Opt_StandaloneDeriving
1330 , Opt_DeriveDataTypeable
1331 , Opt_FlexibleContexts
1332 , Opt_FlexibleInstances
1333 , Opt_ConstrainedClassMethods
1334 , Opt_MultiParamTypeClasses
1335 , Opt_FunctionalDependencies
1337 , Opt_PolymorphicComponents
1338 , Opt_ExistentialQuantification
1341 , Opt_LiberalTypeSynonyms
1345 , Opt_ParallelListComp
1346 , Opt_EmptyDataDecls
1347 , Opt_KindSignatures
1348 , Opt_PatternSignatures
1349 , Opt_GeneralizedNewtypeDeriving
1350 , Opt_TypeFamilies ]
1353 isFlag :: [(String,a)] -> String -> Bool
1354 isFlag flags f = any (\(ff,_) -> ff == f) flags
1356 isPrefFlag :: String -> [(String,a)] -> String -> Bool
1357 isPrefFlag pref flags no_f
1358 | Just f <- maybePrefixMatch pref no_f = isFlag flags f
1362 getFlag :: [(String,a)] -> String -> a
1363 getFlag flags f = case [ opt | (ff, opt) <- flags, ff == f] of
1365 [] -> panic ("get_flag " ++ f)
1367 getPrefFlag :: String -> [(String,a)] -> String -> a
1368 getPrefFlag pref flags f = getFlag flags (fromJust (maybePrefixMatch pref f))
1369 -- We should only be passed flags which match the prefix
1371 -- -----------------------------------------------------------------------------
1372 -- Parsing the dynamic flags.
1374 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1375 parseDynamicFlags dflags args = do
1376 let ((leftover,errs),dflags')
1377 = runCmdLine (processArgs dynamic_flags args) dflags
1378 when (not (null errs)) $ do
1379 throwDyn (UsageError (unlines errs))
1380 return (dflags', leftover)
1383 type DynP = CmdLineP DynFlags
1385 upd :: (DynFlags -> DynFlags) -> DynP ()
1387 dfs <- getCmdLineState
1388 putCmdLineState $! (f dfs)
1390 --------------------------
1391 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1392 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1394 deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1395 -- When you set f, set the ones it implies
1396 -- When you un-set f, however, we don't un-set the things it implies
1397 -- (except for -fno-glasgow-exts, which is treated specially)
1399 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1401 --------------------------
1402 setDumpFlag :: DynFlag -> OptKind DynP
1403 setDumpFlag dump_flag
1404 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1405 -- Whenver we -ddump, switch off the recompilation checker,
1406 -- else you don't see the dump!
1408 setVerbosity :: Maybe Int -> DynP ()
1409 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1411 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1413 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1416 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1418 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1420 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1423 | Nothing <- unpackPackageId pid
1424 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1426 = \s -> s{ thisPackage = pid }
1428 pid = stringToPackageId p
1430 -- If we're linking a binary, then only targets that produce object
1431 -- code are allowed (requests for other target types are ignored).
1432 setTarget l = upd set
1435 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
1438 -- Changes the target only if we're compiling object code. This is
1439 -- used by -fasm and -fvia-C, which switch from one to the other, but
1440 -- not from bytecode to object-code. The idea is that -fasm/-fvia-C
1441 -- can be safely used in an OPTIONS_GHC pragma.
1442 setObjTarget l = upd set
1445 | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1448 setOptLevel :: Int -> DynFlags -> DynFlags
1449 setOptLevel n dflags
1450 | hscTarget dflags == HscInterpreted && n > 0
1452 -- not in IO any more, oh well:
1453 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1455 = updOptLevel n dflags
1458 setMainIs :: String -> DynP ()
1460 | not (null main_fn) && isLower (head main_fn)
1461 -- The arg looked like "Foo.Bar.baz"
1462 = upd $ \d -> d{ mainFunIs = Just main_fn,
1463 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1465 | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar"
1466 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
1468 | otherwise -- The arg looked like "baz"
1469 = upd $ \d -> d{ mainFunIs = Just arg }
1471 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1473 -----------------------------------------------------------------------------
1474 -- Paths & Libraries
1476 -- -i on its own deletes the import paths
1477 addImportPath "" = upd (\s -> s{importPaths = []})
1478 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1482 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1485 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1487 addFrameworkPath p =
1488 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1490 split_marker = ':' -- not configurable (ToDo)
1492 splitPathList :: String -> [String]
1493 splitPathList s = filter notNull (splitUp s)
1494 -- empty paths are ignored: there might be a trailing
1495 -- ':' in the initial list, for example. Empty paths can
1496 -- cause confusion when they are translated into -I options
1497 -- for passing to gcc.
1499 #ifndef mingw32_TARGET_OS
1500 splitUp xs = split split_marker xs
1502 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1504 -- That is, if "foo:bar:baz" is used, this interpreted as
1505 -- consisting of three entries, 'foo', 'bar', 'baz'.
1506 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1507 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1509 -- Notice that no attempt is made to fully replace the 'standard'
1510 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1511 -- that this will cause too much breakage for users & ':' will
1512 -- work fine even with DOS paths, if you're not insisting on being silly.
1515 splitUp (x:':':div:xs) | div `elem` dir_markers
1516 = ((x:':':div:p): splitUp rs)
1518 (p,rs) = findNextPath xs
1519 -- we used to check for existence of the path here, but that
1520 -- required the IO monad to be threaded through the command-line
1521 -- parser which is quite inconvenient. The
1522 splitUp xs = cons p (splitUp rs)
1524 (p,rs) = findNextPath xs
1529 -- will be called either when we've consumed nought or the
1530 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1531 -- finding the next split marker.
1533 case break (`elem` split_markers) xs of
1534 (p, d:ds) -> (p, ds)
1537 split_markers :: [Char]
1538 split_markers = [':', ';']
1540 dir_markers :: [Char]
1541 dir_markers = ['/', '\\']
1544 -- -----------------------------------------------------------------------------
1545 -- tmpDir, where we store temporary files.
1547 setTmpDir :: FilePath -> DynFlags -> DynFlags
1548 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1550 #if !defined(mingw32_HOST_OS)
1551 canonicalise p = normalisePath p
1553 -- Canonicalisation of temp path under win32 is a bit more
1554 -- involved: (a) strip trailing slash,
1555 -- (b) normalise slashes
1556 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1558 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1560 -- if we're operating under cygwin, and TMP/TEMP is of
1561 -- the form "/cygdrive/drive/path", translate this to
1562 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1563 -- understand /cygdrive paths.)
1565 | "/cygdrive/" `isPrefixOf` path =
1566 case drop (length "/cygdrive/") path of
1567 drive:xs@('/':_) -> drive:':':xs
1571 -- strip the trailing backslash (awful, but we only do this once).
1572 removeTrailingSlash path =
1579 -----------------------------------------------------------------------------
1582 setOptHpcDir :: String -> DynP ()
1583 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1585 -----------------------------------------------------------------------------
1586 -- Via-C compilation stuff
1588 -- There are some options that we need to pass to gcc when compiling
1589 -- Haskell code via C, but are only supported by recent versions of
1590 -- gcc. The configure script decides which of these options we need,
1591 -- and puts them in the file "extra-gcc-opts" in $topdir, which is
1592 -- read before each via-C compilation. The advantage of having these
1593 -- in a separate file is that the file can be created at install-time
1594 -- depending on the available gcc version, and even re-generated later
1595 -- if gcc is upgraded.
1597 -- The options below are not dependent on the version of gcc, only the
1600 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1601 [String]) -- for registerised HC compilations
1602 machdepCCOpts dflags
1603 #if alpha_TARGET_ARCH
1605 #ifdef HAVE_THREADED_RTS_SUPPORT
1609 -- For now, to suppress the gcc warning "call-clobbered
1610 -- register used for global register variable", we simply
1611 -- disable all warnings altogether using the -w flag. Oh well.
1613 #elif hppa_TARGET_ARCH
1614 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1615 -- (very nice, but too bad the HP /usr/include files don't agree.)
1616 = ( ["-D_HPUX_SOURCE"], [] )
1618 #elif m68k_TARGET_ARCH
1619 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1620 -- popping of args to routines to be explicit; if we let things
1621 -- be deferred 'til after an STGJUMP, imminent death is certain!
1623 -- -fomit-frame-pointer : *don't*
1624 -- It's better to have a6 completely tied up being a frame pointer
1625 -- rather than let GCC pick random things to do with it.
1626 -- (If we want to steal a6, then we would try to do things
1627 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1628 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1630 #elif i386_TARGET_ARCH
1631 -- -fno-defer-pop : basically the same game as for m68k
1633 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1634 -- the fp (%ebp) for our register maps.
1635 = let n_regs = stolen_x86_regs dflags
1638 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1639 -- , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else ""
1642 "-fomit-frame-pointer",
1643 -- we want -fno-builtin, because when gcc inlines
1644 -- built-in functions like memcpy() it tends to
1645 -- run out of registers, requiring -monly-n-regs
1647 "-DSTOLEN_X86_REGS="++show n_regs ]
1650 #elif ia64_TARGET_ARCH
1651 = ( [], ["-fomit-frame-pointer", "-G0"] )
1653 #elif x86_64_TARGET_ARCH
1654 = ( [], ["-fomit-frame-pointer",
1655 "-fno-asynchronous-unwind-tables",
1656 -- the unwind tables are unnecessary for HC code,
1657 -- and get in the way of -split-objs. Another option
1658 -- would be to throw them away in the mangler, but this
1661 -- calling builtins like strlen() using the FFI can
1662 -- cause gcc to run out of regs, so use the external
1666 #elif sparc_TARGET_ARCH
1668 -- For now, to suppress the gcc warning "call-clobbered
1669 -- register used for global register variable", we simply
1670 -- disable all warnings altogether using the -w flag. Oh well.
1672 #elif powerpc_apple_darwin_TARGET
1674 -- Disable Apple's precompiling preprocessor. It's a great thing
1675 -- for "normal" programs, but it doesn't support register variable
1677 = ( [], ["-no-cpp-precomp"] )
1682 picCCOpts :: DynFlags -> [String]
1684 #if darwin_TARGET_OS
1685 -- Apple prefers to do things the other way round.
1686 -- PIC is on by default.
1687 -- -mdynamic-no-pic:
1688 -- Turn off PIC code generation.
1690 -- Don't generate "common" symbols - these are unwanted
1691 -- in dynamic libraries.
1694 = ["-fno-common", "-D__PIC__"]
1696 = ["-mdynamic-no-pic"]
1697 #elif mingw32_TARGET_OS
1698 -- no -fPIC for Windows
1705 = ["-fPIC", "-D__PIC__"]
1710 -- -----------------------------------------------------------------------------
1714 can_split = cSplitObjs == "YES"
1716 -- -----------------------------------------------------------------------------
1719 compilerInfo :: [(String, String)]
1720 compilerInfo = [("Project name", cProjectName),
1721 ("Project version", cProjectVersion),
1722 ("Booter version", cBooterVersion),
1724 ("Interface file version", cHscIfaceFileVersion),
1725 ("Have interpreter", cGhcWithInterpreter),
1726 ("Object splitting", cSplitObjs),
1727 ("Have native code generator", cGhcWithNativeCodeGen),
1728 ("Support SMP", cGhcWithSMP),
1729 ("Unregisterised", cGhcUnregisterised),
1730 ("Tables next to code", cGhcEnableTablesNextToCode),
1731 ("Win32 DLLs", cEnableWin32DLLs),
1732 ("RTS ways", cGhcRTSWays),
1733 ("Leading underscore", cLeadingUnderscore)]