2 {-# OPTIONS -fno-warn-missing-fields #-}
3 -----------------------------------------------------------------------------
7 -- Most flags are dynamic flags, which means they can change from
8 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
9 -- multi-session GHC each session can be using different dynamic
10 -- flags. Dynamic flags can also be set at the prompt in GHCi.
12 -- (c) The University of Glasgow 2005
14 -----------------------------------------------------------------------------
20 HscTarget(..), isObjectTarget, defaultObjectTarget,
21 GhcMode(..), isOneShot,
22 GhcLink(..), isNoLink,
26 -- Configuration of the core-to-core and stg-to-stg phases
30 SimplifierMode(..), FloatOutSwitches(..),
31 getCoreToDo, getStgToDo,
33 -- Manipulating DynFlags
34 defaultDynFlags, -- DynFlags
35 initDynFlags, -- DynFlags -> IO DynFlags
37 dopt, -- DynFlag -> DynFlags -> Bool
38 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
39 getOpts, -- (DynFlags -> [a]) -> IO [a]
50 machdepCCOpts, picCCOpts
53 #include "HsVersions.h"
55 import Module ( Module, mkModuleName, mkModule )
57 import PrelNames ( mAIN )
58 #ifdef i386_TARGET_ARCH
59 import StaticFlags ( opt_Static )
61 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
63 import {-# SOURCE #-} Packages (PackageState)
64 import DriverPhases ( Phase(..), phaseInputExt )
67 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
68 import Panic ( panic, GhcException(..) )
69 import UniqFM ( UniqFM )
70 import Util ( notNull, splitLongestPrefix, normalisePath )
71 import Maybes ( orElse, fromJust )
72 import SrcLoc ( SrcSpan )
74 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
76 import Data.IORef ( readIORef )
77 import Control.Exception ( throwDyn )
78 import Control.Monad ( when )
79 #ifdef mingw32_TARGET_OS
80 import Data.List ( isPrefixOf )
85 import Data.Char ( isUpper, toLower )
86 import System.IO ( hPutStrLn, stderr )
88 -- -----------------------------------------------------------------------------
102 | Opt_D_dump_inlinings
103 | Opt_D_dump_rule_firings
104 | Opt_D_dump_occur_anal
108 | Opt_D_dump_simpl_iterations
117 | Opt_D_dump_worker_wrapper
118 | Opt_D_dump_rn_trace
119 | Opt_D_dump_rn_stats
121 | Opt_D_dump_simpl_stats
122 | Opt_D_dump_tc_trace
123 | Opt_D_dump_if_trace
129 | Opt_D_verbose_core2core
130 | Opt_D_verbose_stg2stg
132 | Opt_D_dump_hi_diffs
133 | Opt_D_dump_minimal_imports
134 | Opt_D_dump_mod_cycles
135 | Opt_D_faststring_stats
140 | Opt_WarnIsError -- -Werror; makes warnings fatal
141 | Opt_WarnDuplicateExports
143 | Opt_WarnImplicitPrelude
144 | Opt_WarnIncompletePatterns
145 | Opt_WarnIncompletePatternsRecUpd
146 | Opt_WarnMissingFields
147 | Opt_WarnMissingMethods
148 | Opt_WarnMissingSigs
149 | Opt_WarnNameShadowing
150 | Opt_WarnOverlappingPatterns
151 | Opt_WarnSimplePatterns
152 | Opt_WarnTypeDefaults
153 | Opt_WarnMonomorphism
154 | Opt_WarnUnusedBinds
155 | Opt_WarnUnusedImports
156 | Opt_WarnUnusedMatches
157 | Opt_WarnDeprecations
158 | Opt_WarnDodgyImports
163 | Opt_AllowOverlappingInstances
164 | Opt_AllowUndecidableInstances
165 | Opt_AllowIncoherentInstances
166 | Opt_MonomorphismRestriction
168 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
171 | Opt_PArr -- Syntactic support for parallel arrays
172 | Opt_Arrows -- Arrow-notation syntax
176 | Opt_ImplicitPrelude
177 | Opt_ScopedTypeVariables
180 | Opt_OverloadedStrings
181 | Opt_DisambiguateRecordFields
182 | Opt_RecordWildCards
185 | Opt_RelaxedPolyRec -- -X=RelaxedPolyRec
186 | Opt_TypeSynonymInstances
187 | Opt_FlexibleContexts
188 | Opt_FlexibleInstances
189 | Opt_MultiParamTypeClasses
190 | Opt_FunctionalDependencies
192 | Opt_PolymorphicComponents
193 | Opt_ExistentialQuantification
197 | Opt_PatternSignatures
198 | Opt_ParallelListComp
199 | Opt_GeneralizedNewtypeDeriving
202 | Opt_PartiallyAppliedClosedTypeSynonyms
207 | Opt_PrintExplicitForalls
215 | Opt_IgnoreInterfacePragmas
216 | Opt_OmitInterfacePragmas
217 | Opt_DoLambdaEtaExpansion
219 | Opt_IgnoreBreakpoints
222 | Opt_UnboxStrictFields
233 | Opt_ExcessPrecision
234 | Opt_ReadUserPackageConf
238 | Opt_HideAllPackages
239 | Opt_PrintBindResult
242 | Opt_BreakOnException
253 data DynFlags = DynFlags {
256 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
257 stgToDo :: Maybe [StgToDo], -- similarly
258 hscTarget :: HscTarget,
259 hscOutName :: String, -- name of the output file
260 extCoreName :: String, -- name of the .core output file
261 verbosity :: Int, -- verbosity level
262 optLevel :: Int, -- optimisation level
263 maxSimplIterations :: Int, -- max simplifier iterations
264 ruleCheck :: Maybe String,
266 specThreshold :: Int, -- Threshold for function specialisation
268 stolen_x86_regs :: Int,
269 cmdlineHcIncludes :: [String], -- -#includes
270 importPaths :: [FilePath],
272 mainFunIs :: Maybe String,
273 ctxtStkDepth :: Int, -- Typechecker context stack depth
275 thisPackage :: PackageId,
278 wayNames :: [WayName], -- way flags from the cmd line
279 buildTag :: String, -- the global "way" (eg. "p" for prof)
280 rtsBuildTag :: String, -- the RTS "way"
283 objectDir :: Maybe String,
284 hiDir :: Maybe String,
285 stubDir :: Maybe String,
291 outputFile :: Maybe String,
292 outputHi :: Maybe String,
294 includePaths :: [String],
295 libraryPaths :: [String],
296 frameworkPaths :: [String], -- used on darwin only
297 cmdlineFrameworks :: [String], -- ditto
298 tmpDir :: String, -- no trailing '/'
300 ghcUsagePath :: FilePath, -- Filled in by SysTools
301 ghciUsagePath :: FilePath, -- ditto
303 hpcDir :: String, -- ^ path to store the .mix files
305 -- options for particular phases
316 -- commands for particular phases
318 pgm_P :: (String,[Option]),
320 pgm_c :: (String,[Option]),
321 pgm_m :: (String,[Option]),
322 pgm_s :: (String,[Option]),
323 pgm_a :: (String,[Option]),
324 pgm_l :: (String,[Option]),
325 pgm_dll :: (String,[Option]),
327 pgm_sysman :: String,
330 extraPkgConfs :: [FilePath],
331 topDir :: FilePath, -- filled in by SysTools
332 systemPackageConfig :: FilePath, -- ditto
333 -- The -package-conf flags given on the command line, in the order
336 packageFlags :: [PackageFlag],
337 -- The -package and -hide-package flags from the command-line
340 -- NB. do not modify this field, it is calculated by
341 -- Packages.initPackages and Packages.updatePackages.
342 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
343 pkgState :: PackageState,
349 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
360 -- | will this target result in an object file on the disk?
361 isObjectTarget :: HscTarget -> Bool
362 isObjectTarget HscC = True
363 isObjectTarget HscAsm = True
364 isObjectTarget _ = False
366 -- | The 'GhcMode' tells us whether we're doing multi-module
367 -- compilation (controlled via the "GHC" API) or one-shot
368 -- (single-module) compilation. This makes a difference primarily to
369 -- the "Finder": in one-shot mode we look for interface files for
370 -- imported modules, but in multi-module mode we look for source files
371 -- in order to check whether they need to be recompiled.
373 = CompManager -- ^ --make, GHCi, etc.
374 | OneShot -- ^ ghc -c Foo.hs
375 | MkDepend -- ^ ghc -M, see Finder for why we need this
378 isOneShot :: GhcMode -> Bool
379 isOneShot OneShot = True
380 isOneShot _other = False
382 -- | What kind of linking to do.
383 data GhcLink -- What to do in the link step, if there is one
384 = NoLink -- Don't link at all
385 | LinkBinary -- Link object code into a binary
386 | LinkInMemory -- Use the in-memory dynamic linker
387 | LinkDynLib -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
390 isNoLink :: GhcLink -> Bool
391 isNoLink NoLink = True
392 isNoLink other = False
395 = ExposePackage String
397 | IgnorePackage String
400 defaultHscTarget = defaultObjectTarget
402 -- | the 'HscTarget' value corresponding to the default way to create
403 -- object files on the current platform.
405 | cGhcWithNativeCodeGen == "YES" = HscAsm
408 initDynFlags dflags = do
409 -- someday these will be dynamic flags
410 ways <- readIORef v_Ways
411 build_tag <- readIORef v_Build_tag
412 rts_build_tag <- readIORef v_RTS_Build_tag
415 buildTag = build_tag,
416 rtsBuildTag = rts_build_tag
421 ghcMode = CompManager,
422 ghcLink = LinkBinary,
425 hscTarget = defaultHscTarget,
430 maxSimplIterations = 4,
434 cmdlineHcIncludes = [],
438 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
440 thisPackage = mainPackageId,
446 objectSuf = phaseInputExt StopLn,
447 hcSuf = phaseInputExt HCc,
450 outputFile = Nothing,
455 cmdlineFrameworks = [],
456 tmpDir = cDEFAULT_TMPDIR,
472 pkgDatabase = Nothing,
473 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
475 Opt_ReadUserPackageConf,
477 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
478 -- behaviour the default, to see if anyone notices
482 Opt_MonomorphismRestriction,
487 Opt_PrintBindResult ]
488 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
489 -- The default -O0 options
492 log_action = \severity srcSpan style msg ->
494 SevInfo -> hPutStrLn stderr (show (msg style))
495 SevFatal -> hPutStrLn stderr (show (msg style))
496 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
502 0 | print errors & warnings only
503 1 | minimal verbosity: print "compiling M ... done." for each module.
504 2 | equivalent to -dshow-passes
505 3 | equivalent to existing "ghc -v"
506 4 | "ghc -v -ddump-most"
507 5 | "ghc -v -ddump-all"
510 dopt :: DynFlag -> DynFlags -> Bool
511 dopt f dflags = f `elem` (flags dflags)
513 dopt_set :: DynFlags -> DynFlag -> DynFlags
514 dopt_set dfs f = dfs{ flags = f : flags dfs }
516 dopt_unset :: DynFlags -> DynFlag -> DynFlags
517 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
519 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
520 getOpts dflags opts = reverse (opts dflags)
521 -- We add to the options from the front, so we need to reverse the list
523 getVerbFlag :: DynFlags -> String
525 | verbosity dflags >= 3 = "-v"
528 setObjectDir f d = d{ objectDir = f}
529 setHiDir f d = d{ hiDir = f}
530 setStubDir f d = d{ stubDir = f}
532 setObjectSuf f d = d{ objectSuf = f}
533 setHiSuf f d = d{ hiSuf = f}
534 setHcSuf f d = d{ hcSuf = f}
536 setOutputFile f d = d{ outputFile = f}
537 setOutputHi f d = d{ outputHi = f}
539 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
540 -- Config.hs should really use Option.
541 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
543 setPgmL f d = d{ pgm_L = f}
544 setPgmF f d = d{ pgm_F = f}
545 setPgmc f d = d{ pgm_c = (f,[])}
546 setPgmm f d = d{ pgm_m = (f,[])}
547 setPgms f d = d{ pgm_s = (f,[])}
548 setPgma f d = d{ pgm_a = (f,[])}
549 setPgml f d = d{ pgm_l = (f,[])}
550 setPgmdll f d = d{ pgm_dll = (f,[])}
552 addOptL f d = d{ opt_L = f : opt_L d}
553 addOptP f d = d{ opt_P = f : opt_P d}
554 addOptF f d = d{ opt_F = f : opt_F d}
555 addOptc f d = d{ opt_c = f : opt_c d}
556 addOptm f d = d{ opt_m = f : opt_m d}
557 addOpta f d = d{ opt_a = f : opt_a d}
558 addOptl f d = d{ opt_l = f : opt_l d}
559 addOptdll f d = d{ opt_dll = f : opt_dll d}
560 addOptdep f d = d{ opt_dep = f : opt_dep d}
562 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
564 -- -----------------------------------------------------------------------------
565 -- Command-line options
567 -- When invoking external tools as part of the compilation pipeline, we
568 -- pass these a sequence of options on the command-line. Rather than
569 -- just using a list of Strings, we use a type that allows us to distinguish
570 -- between filepaths and 'other stuff'. [The reason being, of course, that
571 -- this type gives us a handle on transforming filenames, and filenames only,
572 -- to whatever format they're expected to be on a particular platform.]
575 = FileOption -- an entry that _contains_ filename(s) / filepaths.
576 String -- a non-filepath prefix that shouldn't be
577 -- transformed (e.g., "/out=")
578 String -- the filepath/filename portion
581 -----------------------------------------------------------------------------
582 -- Setting the optimisation level
584 updOptLevel :: Int -> DynFlags -> DynFlags
585 -- Set dynflags appropriate to the optimisation level
587 = dfs2{ optLevel = final_n }
589 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
590 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
591 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
593 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
594 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
596 optLevelFlags :: [([Int], DynFlag)]
598 = [ ([0], Opt_IgnoreInterfacePragmas)
599 , ([0], Opt_OmitInterfacePragmas)
601 , ([1,2], Opt_IgnoreAsserts)
602 , ([1,2], Opt_RewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
604 , ([1,2], Opt_DoEtaReduction)
605 , ([1,2], Opt_CaseMerge)
606 , ([1,2], Opt_Strictness)
608 , ([1,2], Opt_FullLaziness)
610 , ([2], Opt_LiberateCase)
611 , ([2], Opt_SpecConstr)
613 , ([0,1,2], Opt_DoLambdaEtaExpansion)
614 -- This one is important for a tiresome reason:
615 -- we want to make sure that the bindings for data
616 -- constructors are eta-expanded. This is probably
617 -- a good thing anyway, but it seems fragile.
620 -- -----------------------------------------------------------------------------
621 -- Standard sets of warning options
624 = [ Opt_WarnDeprecations,
625 Opt_WarnOverlappingPatterns,
626 Opt_WarnMissingFields,
627 Opt_WarnMissingMethods,
628 Opt_WarnDuplicateExports
632 = standardWarnings ++
633 [ Opt_WarnUnusedBinds,
634 Opt_WarnUnusedMatches,
635 Opt_WarnUnusedImports,
636 Opt_WarnIncompletePatterns,
642 [ Opt_WarnTypeDefaults,
643 Opt_WarnNameShadowing,
649 -- -----------------------------------------------------------------------------
650 -- CoreToDo: abstraction of core-to-core passes to run.
652 data CoreToDo -- These are diff core-to-core passes,
653 -- which may be invoked in any order,
654 -- as many times as you like.
656 = CoreDoSimplify -- The core-to-core simplifier.
659 -- Each run of the simplifier can take a different
660 -- set of simplifier-specific flags.
662 | CoreDoFloatOutwards FloatOutSwitches
667 | CoreDoWorkerWrapper
670 | CoreDoOldStrictness
673 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
674 -- matching this string
675 | CoreDoNothing -- Useful when building up
676 | CoreDoPasses [CoreToDo] -- lists of these things
678 data SimplifierMode -- See comments in SimplMonad
682 data SimplifierSwitch
683 = MaxSimplifierIterations Int
686 data FloatOutSwitches
687 = FloatOutSw Bool -- True <=> float lambdas to top level
688 Bool -- True <=> float constants to top level,
689 -- even if they do not escape a lambda
692 -- The core-to-core pass ordering is derived from the DynFlags:
693 runWhen :: Bool -> CoreToDo -> CoreToDo
694 runWhen True do_this = do_this
695 runWhen False do_this = CoreDoNothing
697 getCoreToDo :: DynFlags -> [CoreToDo]
699 | Just todo <- coreToDo dflags = todo -- set explicitly by user
700 | otherwise = core_todo
702 opt_level = optLevel dflags
703 max_iter = maxSimplIterations dflags
704 strictness = dopt Opt_Strictness dflags
705 full_laziness = dopt Opt_FullLaziness dflags
706 cse = dopt Opt_CSE dflags
707 spec_constr = dopt Opt_SpecConstr dflags
708 liberate_case = dopt Opt_LiberateCase dflags
709 rule_check = ruleCheck dflags
712 if opt_level == 0 then
714 CoreDoSimplify (SimplPhase 0) [
715 MaxSimplifierIterations max_iter
718 else {- opt_level >= 1 -} [
720 -- initial simplify: mk specialiser happy: minimum effort please
721 CoreDoSimplify SimplGently [
723 -- Don't inline anything till full laziness has bitten
724 -- In particular, inlining wrappers inhibits floating
725 -- e.g. ...(case f x of ...)...
726 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
727 -- ==> ...(case x of I# x# -> case fw x# of ...)...
728 -- and now the redex (f x) isn't floatable any more
729 -- Similarly, don't apply any rules until after full
730 -- laziness. Notably, list fusion can prevent floating.
732 NoCaseOfCase, -- Don't do case-of-case transformations.
733 -- This makes full laziness work better
734 MaxSimplifierIterations max_iter
737 -- Specialisation is best done before full laziness
738 -- so that overloaded functions have all their dictionary lambdas manifest
741 runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
745 CoreDoSimplify (SimplPhase 2) [
746 -- Want to run with inline phase 2 after the specialiser to give
747 -- maximum chance for fusion to work before we inline build/augment
748 -- in phase 1. This made a difference in 'ansi' where an
749 -- overloaded function wasn't inlined till too late.
750 MaxSimplifierIterations max_iter
752 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
754 CoreDoSimplify (SimplPhase 1) [
755 -- Need inline-phase2 here so that build/augment get
756 -- inlined. I found that spectral/hartel/genfft lost some useful
757 -- strictness in the function sumcode' if augment is not inlined
758 -- before strictness analysis runs
759 MaxSimplifierIterations max_iter
761 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
763 CoreDoSimplify (SimplPhase 0) [
764 -- Phase 0: allow all Ids to be inlined now
765 -- This gets foldr inlined before strictness analysis
767 MaxSimplifierIterations 3
768 -- At least 3 iterations because otherwise we land up with
769 -- huge dead expressions because of an infelicity in the
771 -- let k = BIG in foldr k z xs
772 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
773 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
777 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
779 #ifdef OLD_STRICTNESS
782 runWhen strictness (CoreDoPasses [
786 CoreDoSimplify (SimplPhase 0) [
787 MaxSimplifierIterations max_iter
790 runWhen full_laziness
791 (CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
792 True)), -- Float constants
793 -- nofib/spectral/hartel/wang doubles in speed if you
794 -- do full laziness late in the day. It only happens
795 -- after fusion and other stuff, so the early pass doesn't
796 -- catch it. For the record, the redex is
797 -- f_el22 (f_el21 r_midblock)
801 -- We want CSE to follow the final full-laziness pass, because it may
802 -- succeed in commoning up things floated out by full laziness.
803 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
807 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
809 -- Case-liberation for -O2. This should be after
810 -- strictness analysis and the simplification which follows it.
811 runWhen liberate_case (CoreDoPasses [
813 CoreDoSimplify (SimplPhase 0) [
814 MaxSimplifierIterations max_iter
815 ] ]), -- Run the simplifier after LiberateCase to vastly
816 -- reduce the possiblility of shadowing
817 -- Reason: see Note [Shadowing] in SpecConstr.lhs
819 runWhen spec_constr CoreDoSpecConstr,
821 -- Final clean-up simplification:
822 CoreDoSimplify (SimplPhase 0) [
823 MaxSimplifierIterations max_iter
827 -- -----------------------------------------------------------------------------
828 -- StgToDo: abstraction of stg-to-stg passes to run.
831 = StgDoMassageForProfiling -- should be (next to) last
832 -- There's also setStgVarInfo, but its absolute "lastness"
833 -- is so critical that it is hardwired in (no flag).
836 getStgToDo :: DynFlags -> [StgToDo]
838 | Just todo <- stgToDo dflags = todo -- set explicitly by user
841 stg_stats = dopt Opt_StgStats dflags
843 todo1 = if stg_stats then [D_stg_stats] else []
845 todo2 | WayProf `elem` wayNames dflags
846 = StgDoMassageForProfiling : todo1
850 -- -----------------------------------------------------------------------------
854 allFlags = map ('-':) $
855 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
856 map ("fno-"++) flags ++
858 where ok (PrefixPred _ _) = False
860 flags = map fst fFlags
862 dynamic_flags :: [(String, OptKind DynP)]
864 ( "n" , NoArg (setDynFlag Opt_DryRun) )
865 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
866 , ( "F" , NoArg (setDynFlag Opt_Pp))
867 , ( "#include" , HasArg (addCmdlineHCInclude) )
868 , ( "v" , OptIntSuffix setVerbosity )
870 ------- Specific phases --------------------------------------------
871 , ( "pgmL" , HasArg (upd . setPgmL) )
872 , ( "pgmP" , HasArg (upd . setPgmP) )
873 , ( "pgmF" , HasArg (upd . setPgmF) )
874 , ( "pgmc" , HasArg (upd . setPgmc) )
875 , ( "pgmm" , HasArg (upd . setPgmm) )
876 , ( "pgms" , HasArg (upd . setPgms) )
877 , ( "pgma" , HasArg (upd . setPgma) )
878 , ( "pgml" , HasArg (upd . setPgml) )
879 , ( "pgmdll" , HasArg (upd . setPgmdll) )
881 , ( "optL" , HasArg (upd . addOptL) )
882 , ( "optP" , HasArg (upd . addOptP) )
883 , ( "optF" , HasArg (upd . addOptF) )
884 , ( "optc" , HasArg (upd . addOptc) )
885 , ( "optm" , HasArg (upd . addOptm) )
886 , ( "opta" , HasArg (upd . addOpta) )
887 , ( "optl" , HasArg (upd . addOptl) )
888 , ( "optdll" , HasArg (upd . addOptdll) )
889 , ( "optdep" , HasArg (upd . addOptdep) )
891 , ( "split-objs" , NoArg (if can_split
892 then setDynFlag Opt_SplitObjs
895 -------- Linking ----------------------------------------------------
896 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
897 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
898 , ( "shared" , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
900 ------- Libraries ---------------------------------------------------
901 , ( "L" , Prefix addLibraryPath )
902 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
905 ------- Frameworks --------------------------------------------------
906 -- -framework-path should really be -F ...
907 , ( "framework-path" , HasArg addFrameworkPath )
908 , ( "framework" , HasArg (upd . addCmdlineFramework) )
910 ------- Output Redirection ------------------------------------------
911 , ( "odir" , HasArg (upd . setObjectDir . Just))
912 , ( "o" , SepArg (upd . setOutputFile . Just))
913 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
914 , ( "osuf" , HasArg (upd . setObjectSuf))
915 , ( "hcsuf" , HasArg (upd . setHcSuf))
916 , ( "hisuf" , HasArg (upd . setHiSuf))
917 , ( "hidir" , HasArg (upd . setHiDir . Just))
918 , ( "tmpdir" , HasArg (upd . setTmpDir))
919 , ( "stubdir" , HasArg (upd . setStubDir . Just))
921 ------- Keeping temporary files -------------------------------------
922 -- These can be singular (think ghc -c) or plural (think ghc --make)
923 , ( "keep-hc-file" , NoArg (setDynFlag Opt_KeepHcFiles))
924 , ( "keep-hc-files" , NoArg (setDynFlag Opt_KeepHcFiles))
925 , ( "keep-s-file" , NoArg (setDynFlag Opt_KeepSFiles))
926 , ( "keep-s-files" , NoArg (setDynFlag Opt_KeepSFiles))
927 , ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
928 , ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
929 -- This only makes sense as plural
930 , ( "keep-tmp-files" , NoArg (setDynFlag Opt_KeepTmpFiles))
932 ------- Miscellaneous ----------------------------------------------
933 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
934 , ( "main-is" , SepArg setMainIs )
935 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
936 , ( "hpcdir" , SepArg setOptHpcDir )
938 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
939 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
940 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
942 ------- Packages ----------------------------------------------------
943 , ( "package-conf" , HasArg extraPkgConf_ )
944 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
945 , ( "package-name" , HasArg (upd . setPackageName) )
946 , ( "package" , HasArg exposePackage )
947 , ( "hide-package" , HasArg hidePackage )
948 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
949 , ( "ignore-package" , HasArg ignorePackage )
950 , ( "syslib" , HasArg exposePackage ) -- for compatibility
952 ------ HsCpp opts ---------------------------------------------------
953 , ( "D", AnySuffix (upd . addOptP) )
954 , ( "U", AnySuffix (upd . addOptP) )
956 ------- Include/Import Paths ----------------------------------------
957 , ( "I" , Prefix addIncludePath)
958 , ( "i" , OptPrefix addImportPath )
960 ------ Debugging ----------------------------------------------------
961 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
963 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
964 , ( "ddump-cps-cmm", setDumpFlag Opt_D_dump_cps_cmm)
965 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
966 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
967 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
968 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
969 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
970 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
971 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
972 , ( "ddump-rule-firings", setDumpFlag Opt_D_dump_rule_firings)
973 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
974 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
975 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
976 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
977 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
978 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
979 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
980 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
981 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
982 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
983 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
984 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
985 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
986 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
987 , ( "ddump-rn-trace", setDumpFlag Opt_D_dump_rn_trace)
988 , ( "ddump-if-trace", setDumpFlag Opt_D_dump_if_trace)
989 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
990 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
991 , ( "ddump-rn-stats", setDumpFlag Opt_D_dump_rn_stats)
992 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
993 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
994 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
995 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
996 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
997 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
998 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
999 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
1000 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
1001 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
1002 , ( "ddump-mod-cycles", setDumpFlag Opt_D_dump_mod_cycles)
1004 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
1005 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
1006 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
1007 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
1008 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
1009 setVerbosity (Just 2)) )
1010 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
1012 ------ Machine dependant (-m<blah>) stuff ---------------------------
1014 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1015 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1016 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1018 ------ Warning opts -------------------------------------------------
1019 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
1020 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
1021 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
1022 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
1023 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
1025 ------ Optimisation flags ------------------------------------------
1026 , ( "O" , NoArg (upd (setOptLevel 1)))
1027 , ( "Onot" , NoArg (upd (setOptLevel 0)))
1028 , ( "O" , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1029 -- If the number is missing, use 1
1031 , ( "fmax-simplifier-iterations", IntSuffix (\n ->
1032 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1034 -- liberate-case-threshold is an old flag for '-fspec-threshold'
1035 , ( "fspec-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1036 , ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1038 , ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1039 , ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1041 ------ Compiler flags -----------------------------------------------
1043 , ( "fasm", NoArg (setObjTarget HscAsm) )
1044 , ( "fvia-c", NoArg (setObjTarget HscC) )
1045 , ( "fvia-C", NoArg (setObjTarget HscC) )
1047 , ( "fno-code", NoArg (setTarget HscNothing))
1048 , ( "fbyte-code", NoArg (setTarget HscInterpreted) )
1049 , ( "fobject-code", NoArg (setTarget defaultHscTarget) )
1051 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
1052 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1054 -- the rest of the -f* and -fno-* flags
1055 , ( "f", PrefixPred (isFlag fFlags) (\f -> setDynFlag (getFlag fFlags f)) )
1056 , ( "f", PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1058 -- For now, allow -X flags with -f; ToDo: report this as deprecated
1059 , ( "f", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1060 , ( "f", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1062 -- the rest of the -X* and -Xno-* flags
1063 , ( "X", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1064 , ( "X", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1067 -- these -f<blah> flags can all be reversed with -fno-<blah>
1070 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1071 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1072 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude ),
1073 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1074 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1075 ( "warn-missing-fields", Opt_WarnMissingFields ),
1076 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1077 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1078 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1079 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1080 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1081 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1082 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism ),
1083 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1084 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1085 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1086 ( "warn-deprecations", Opt_WarnDeprecations ),
1087 ( "warn-orphans", Opt_WarnOrphans ),
1088 ( "warn-tabs", Opt_WarnTabs ),
1089 ( "print-explicit-foralls", Opt_PrintExplicitForalls ),
1090 ( "strictness", Opt_Strictness ),
1091 ( "full-laziness", Opt_FullLaziness ),
1092 ( "liberate-case", Opt_LiberateCase ),
1093 ( "spec-constr", Opt_SpecConstr ),
1095 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1096 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1097 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1098 ( "ignore-asserts", Opt_IgnoreAsserts ),
1099 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1100 ( "do-eta-reduction", Opt_DoEtaReduction ),
1101 ( "case-merge", Opt_CaseMerge ),
1102 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1103 ( "dicts-cheap", Opt_DictsCheap ),
1104 ( "excess-precision", Opt_ExcessPrecision ),
1105 ( "asm-mangling", Opt_DoAsmMangling ),
1106 ( "print-bind-result", Opt_PrintBindResult ),
1107 ( "force-recomp", Opt_ForceRecomp ),
1108 ( "hpc-no-auto", Opt_Hpc_No_Auto ),
1109 ( "rewrite-rules", Opt_RewriteRules ),
1110 ( "break-on-exception", Opt_BreakOnException ),
1111 ( "vectorise", Opt_Vectorise )
1115 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1116 xFlags :: [(String, DynFlag)]
1119 ( "PatternGuards", Opt_PatternGuards ),
1120 ( "UnicodeSyntax", Opt_UnicodeSyntax ),
1121 ( "MagicHash", Opt_MagicHash ),
1122 ( "PolymorphicComponents", Opt_PolymorphicComponents ),
1123 ( "ExistentialQuantification", Opt_ExistentialQuantification ),
1124 ( "KindSignatures", Opt_KindSignatures ),
1125 ( "PatternSignatures", Opt_PatternSignatures ),
1126 ( "EmptyDataDecls", Opt_EmptyDataDecls ),
1127 ( "ParallelListComp", Opt_ParallelListComp ),
1128 ( "FI", Opt_FFI ), -- support `-ffi'...
1129 ( "FFI", Opt_FFI ), -- ...and also `-fffi'
1130 ( "ForeignFunctionInterface", Opt_FFI ),
1132 ( "PartiallyAppliedClosedTypeSynonyms", Opt_PartiallyAppliedClosedTypeSynonyms ),
1133 ( "Rank2Types", Opt_Rank2Types ),
1134 ( "RankNTypes", Opt_RankNTypes ),
1135 ( "TypeOperators", Opt_TypeOperators ),
1136 ( "RecursiveDo", Opt_RecursiveDo ),
1137 ( "Arrows", Opt_Arrows ), -- arrow syntax
1138 ( "Parr", Opt_PArr ),
1140 ( "TH", Opt_TH ), -- support -fth
1141 ( "TemplateHaskelll", Opt_TH ),
1143 ( "Generics", Opt_Generics ),
1145 ( "ImplicitPrelude", Opt_ImplicitPrelude ), -- On by default
1147 ( "RecordWildCards", Opt_RecordWildCards ),
1148 ( "RecordPuns", Opt_RecordPuns ),
1149 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields ),
1151 ( "OverloadedStrings", Opt_OverloadedStrings ),
1152 ( "GADTs", Opt_GADTs ),
1153 ( "TypeFamilies", Opt_TypeFamilies ),
1154 ( "BangPatterns", Opt_BangPatterns ),
1155 ( "MonomorphismRestriction", Opt_MonomorphismRestriction ), -- On by default
1156 ( "MonoPatBinds", Opt_MonoPatBinds ), -- On by default (which is not strictly H98)
1157 ( "RelaxedPolyRec", Opt_RelaxedPolyRec),
1158 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules ),
1159 ( "ImplicitParams", Opt_ImplicitParams ),
1160 ( "ScopedTypeVariables", Opt_ScopedTypeVariables ),
1161 ( "TypeSynonymInstances", Opt_TypeSynonymInstances ),
1162 ( "FlexibleContexts", Opt_FlexibleContexts ),
1163 ( "FlexibleInstances", Opt_FlexibleInstances ),
1164 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses ),
1165 ( "FunctionalDependencies", Opt_FunctionalDependencies ),
1166 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving ),
1167 ( "AllowOverlappingInstances", Opt_AllowOverlappingInstances ),
1168 ( "AllowUndecidableInstances", Opt_AllowUndecidableInstances ),
1169 ( "AllowIncoherentInstances", Opt_AllowIncoherentInstances )
1172 impliedFlags :: [(DynFlag, [DynFlag])]
1174 ( Opt_GADTs, [Opt_RelaxedPolyRec] ) -- We want type-sig variables to be completely rigid for GADTs
1177 glasgowExtsFlags = [ Opt_GlasgowExts
1178 , Opt_PrintExplicitForalls
1181 , Opt_ImplicitParams
1182 , Opt_ScopedTypeVariables
1183 , Opt_TypeSynonymInstances
1184 , Opt_FlexibleContexts
1185 , Opt_FlexibleInstances
1186 , Opt_MultiParamTypeClasses
1187 , Opt_FunctionalDependencies
1189 , Opt_PolymorphicComponents
1190 , Opt_ExistentialQuantification
1193 , Opt_PartiallyAppliedClosedTypeSynonyms
1197 , Opt_ParallelListComp
1198 , Opt_EmptyDataDecls
1199 , Opt_KindSignatures
1200 , Opt_PatternSignatures
1201 , Opt_GeneralizedNewtypeDeriving
1202 , Opt_TypeFamilies ]
1205 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1207 isFlag flags f = is_flag flags (normaliseFlag f)
1210 | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1213 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1214 -- nf is normalised alreadly
1217 getFlag, getNoFlag :: [(String,a)] -> String -> a
1219 getFlag flags f = get_flag flags (normaliseFlag f)
1221 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1222 -- The flag should be a no-flag already
1224 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1226 [] -> panic ("get_flag " ++ nf)
1229 noFlag_maybe :: String -> Maybe String
1230 -- The input is normalised already
1231 noFlag_maybe ('n' : 'o' : f) = Just f
1232 noFlag_maybe other = Nothing
1234 normaliseFlag :: String -> String
1235 -- Normalise a option flag by
1236 -- * map to lower case
1237 -- * removing hyphens
1238 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1239 normaliseFlag [] = []
1240 normaliseFlag ('-':s) = normaliseFlag s
1241 normaliseFlag (c:s) = toLower c : normaliseFlag s
1243 -- -----------------------------------------------------------------------------
1244 -- Parsing the dynamic flags.
1246 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1247 parseDynamicFlags dflags args = do
1248 let ((leftover,errs),dflags')
1249 = runCmdLine (processArgs dynamic_flags args) dflags
1250 when (not (null errs)) $ do
1251 throwDyn (UsageError (unlines errs))
1252 return (dflags', leftover)
1255 type DynP = CmdLineP DynFlags
1257 upd :: (DynFlags -> DynFlags) -> DynP ()
1259 dfs <- getCmdLineState
1260 putCmdLineState $! (f dfs)
1262 --------------------------
1263 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1264 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1266 deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1267 -- When you set f, set the ones it implies
1268 -- When you un-set f, however, we don't un-set the things it implies
1269 -- (except for -fno-glasgow-exts, which is treated specially)
1271 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1273 --------------------------
1274 setDumpFlag :: DynFlag -> OptKind DynP
1275 setDumpFlag dump_flag
1276 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1277 -- Whenver we -ddump, switch off the recompilation checker,
1278 -- else you don't see the dump!
1280 setVerbosity :: Maybe Int -> DynP ()
1281 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1283 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1285 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1288 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1290 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1292 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1295 | Nothing <- unpackPackageId pid
1296 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1298 = \s -> s{ thisPackage = pid }
1300 pid = stringToPackageId p
1302 -- If we're linking a binary, then only targets that produce object
1303 -- code are allowed (requests for other target types are ignored).
1304 setTarget l = upd set
1307 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
1310 -- Changes the target only if we're compiling object code. This is
1311 -- used by -fasm and -fvia-C, which switch from one to the other, but
1312 -- not from bytecode to object-code. The idea is that -fasm/-fvia-C
1313 -- can be safely used in an OPTIONS_GHC pragma.
1314 setObjTarget l = upd set
1317 | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1320 setOptLevel :: Int -> DynFlags -> DynFlags
1321 setOptLevel n dflags
1322 | hscTarget dflags == HscInterpreted && n > 0
1324 -- not in IO any more, oh well:
1325 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1327 = updOptLevel n dflags
1330 setMainIs :: String -> DynP ()
1332 | not (null main_fn) -- The arg looked like "Foo.baz"
1333 = upd $ \d -> d{ mainFunIs = Just main_fn,
1334 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1336 | isUpper (head main_mod) -- The arg looked like "Foo"
1337 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1339 | otherwise -- The arg looked like "baz"
1340 = upd $ \d -> d{ mainFunIs = Just main_mod }
1342 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1344 -----------------------------------------------------------------------------
1345 -- Paths & Libraries
1347 -- -i on its own deletes the import paths
1348 addImportPath "" = upd (\s -> s{importPaths = []})
1349 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1353 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1356 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1358 addFrameworkPath p =
1359 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1361 split_marker = ':' -- not configurable (ToDo)
1363 splitPathList :: String -> [String]
1364 splitPathList s = filter notNull (splitUp s)
1365 -- empty paths are ignored: there might be a trailing
1366 -- ':' in the initial list, for example. Empty paths can
1367 -- cause confusion when they are translated into -I options
1368 -- for passing to gcc.
1370 #ifndef mingw32_TARGET_OS
1371 splitUp xs = split split_marker xs
1373 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1375 -- That is, if "foo:bar:baz" is used, this interpreted as
1376 -- consisting of three entries, 'foo', 'bar', 'baz'.
1377 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1378 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1380 -- Notice that no attempt is made to fully replace the 'standard'
1381 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1382 -- that this will cause too much breakage for users & ':' will
1383 -- work fine even with DOS paths, if you're not insisting on being silly.
1386 splitUp (x:':':div:xs) | div `elem` dir_markers
1387 = ((x:':':div:p): splitUp rs)
1389 (p,rs) = findNextPath xs
1390 -- we used to check for existence of the path here, but that
1391 -- required the IO monad to be threaded through the command-line
1392 -- parser which is quite inconvenient. The
1393 splitUp xs = cons p (splitUp rs)
1395 (p,rs) = findNextPath xs
1400 -- will be called either when we've consumed nought or the
1401 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1402 -- finding the next split marker.
1404 case break (`elem` split_markers) xs of
1405 (p, d:ds) -> (p, ds)
1408 split_markers :: [Char]
1409 split_markers = [':', ';']
1411 dir_markers :: [Char]
1412 dir_markers = ['/', '\\']
1415 -- -----------------------------------------------------------------------------
1416 -- tmpDir, where we store temporary files.
1418 setTmpDir :: FilePath -> DynFlags -> DynFlags
1419 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1421 #if !defined(mingw32_HOST_OS)
1422 canonicalise p = normalisePath p
1424 -- Canonicalisation of temp path under win32 is a bit more
1425 -- involved: (a) strip trailing slash,
1426 -- (b) normalise slashes
1427 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1429 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1431 -- if we're operating under cygwin, and TMP/TEMP is of
1432 -- the form "/cygdrive/drive/path", translate this to
1433 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1434 -- understand /cygdrive paths.)
1436 | "/cygdrive/" `isPrefixOf` path =
1437 case drop (length "/cygdrive/") path of
1438 drive:xs@('/':_) -> drive:':':xs
1442 -- strip the trailing backslash (awful, but we only do this once).
1443 removeTrailingSlash path =
1450 -----------------------------------------------------------------------------
1453 setOptHpcDir :: String -> DynP ()
1454 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1456 -----------------------------------------------------------------------------
1457 -- Via-C compilation stuff
1459 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1460 [String]) -- for registerised HC compilations
1461 machdepCCOpts dflags
1462 #if alpha_TARGET_ARCH
1464 #ifdef HAVE_THREADED_RTS_SUPPORT
1468 -- For now, to suppress the gcc warning "call-clobbered
1469 -- register used for global register variable", we simply
1470 -- disable all warnings altogether using the -w flag. Oh well.
1472 #elif hppa_TARGET_ARCH
1473 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1474 -- (very nice, but too bad the HP /usr/include files don't agree.)
1475 = ( ["-D_HPUX_SOURCE"], [] )
1477 #elif m68k_TARGET_ARCH
1478 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1479 -- popping of args to routines to be explicit; if we let things
1480 -- be deferred 'til after an STGJUMP, imminent death is certain!
1482 -- -fomit-frame-pointer : *don't*
1483 -- It's better to have a6 completely tied up being a frame pointer
1484 -- rather than let GCC pick random things to do with it.
1485 -- (If we want to steal a6, then we would try to do things
1486 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1487 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1489 #elif i386_TARGET_ARCH
1490 -- -fno-defer-pop : basically the same game as for m68k
1492 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1493 -- the fp (%ebp) for our register maps.
1494 = let n_regs = stolen_x86_regs dflags
1497 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1498 -- , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else ""
1501 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1502 -- Some gccs are configured with
1503 -- -momit-leaf-frame-pointer on by default, and it
1504 -- apparently takes precedence over
1505 -- -fomit-frame-pointer, so we disable it first here.
1506 "-mno-omit-leaf-frame-pointer",
1508 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1509 "-fno-unit-at-a-time",
1510 -- unit-at-a-time doesn't do us any good, and screws
1511 -- up -split-objs by moving the split markers around.
1512 -- It's only turned on with -O2, but put it here just
1513 -- in case someone uses -optc-O2.
1515 "-fomit-frame-pointer",
1516 -- we want -fno-builtin, because when gcc inlines
1517 -- built-in functions like memcpy() it tends to
1518 -- run out of registers, requiring -monly-n-regs
1520 "-DSTOLEN_X86_REGS="++show n_regs ]
1523 #elif ia64_TARGET_ARCH
1524 = ( [], ["-fomit-frame-pointer", "-G0"] )
1526 #elif x86_64_TARGET_ARCH
1527 = ( [], ["-fomit-frame-pointer",
1528 "-fno-asynchronous-unwind-tables",
1529 -- the unwind tables are unnecessary for HC code,
1530 -- and get in the way of -split-objs. Another option
1531 -- would be to throw them away in the mangler, but this
1533 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1534 "-fno-unit-at-a-time",
1535 -- unit-at-a-time doesn't do us any good, and screws
1536 -- up -split-objs by moving the split markers around.
1537 -- It's only turned on with -O2, but put it here just
1538 -- in case someone uses -optc-O2.
1541 -- calling builtins like strlen() using the FFI can
1542 -- cause gcc to run out of regs, so use the external
1546 #elif sparc_TARGET_ARCH
1548 -- For now, to suppress the gcc warning "call-clobbered
1549 -- register used for global register variable", we simply
1550 -- disable all warnings altogether using the -w flag. Oh well.
1552 #elif powerpc_apple_darwin_TARGET
1554 -- Disable Apple's precompiling preprocessor. It's a great thing
1555 -- for "normal" programs, but it doesn't support register variable
1557 = ( [], ["-no-cpp-precomp"] )
1562 picCCOpts :: DynFlags -> [String]
1564 #if darwin_TARGET_OS
1565 -- Apple prefers to do things the other way round.
1566 -- PIC is on by default.
1567 -- -mdynamic-no-pic:
1568 -- Turn off PIC code generation.
1570 -- Don't generate "common" symbols - these are unwanted
1571 -- in dynamic libraries.
1576 = ["-mdynamic-no-pic"]
1577 #elif mingw32_TARGET_OS
1578 -- no -fPIC for Windows
1587 -- -----------------------------------------------------------------------------
1592 #if defined(i386_TARGET_ARCH) \
1593 || defined(x86_64_TARGET_ARCH) \
1594 || defined(alpha_TARGET_ARCH) \
1595 || defined(hppa_TARGET_ARCH) \
1596 || defined(m68k_TARGET_ARCH) \
1597 || defined(mips_TARGET_ARCH) \
1598 || defined(powerpc_TARGET_ARCH) \
1599 || defined(rs6000_TARGET_ARCH) \
1600 || defined(sparc_TARGET_ARCH)