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_FlexibleInstances
188 | Opt_MultiParamTypeClasses
189 | Opt_FunctionalDependencies
193 | Opt_ParallelListComp
194 | Opt_GeneralizedNewtypeDeriving
206 | Opt_IgnoreInterfacePragmas
207 | Opt_OmitInterfacePragmas
208 | Opt_DoLambdaEtaExpansion
210 | Opt_IgnoreBreakpoints
213 | Opt_UnboxStrictFields
224 | Opt_ExcessPrecision
225 | Opt_ReadUserPackageConf
229 | Opt_HideAllPackages
230 | Opt_PrintBindResult
233 | Opt_BreakOnException
244 data DynFlags = DynFlags {
247 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
248 stgToDo :: Maybe [StgToDo], -- similarly
249 hscTarget :: HscTarget,
250 hscOutName :: String, -- name of the output file
251 extCoreName :: String, -- name of the .core output file
252 verbosity :: Int, -- verbosity level
253 optLevel :: Int, -- optimisation level
254 maxSimplIterations :: Int, -- max simplifier iterations
255 ruleCheck :: Maybe String,
257 specThreshold :: Int, -- Threshold for function specialisation
259 stolen_x86_regs :: Int,
260 cmdlineHcIncludes :: [String], -- -#includes
261 importPaths :: [FilePath],
263 mainFunIs :: Maybe String,
264 ctxtStkDepth :: Int, -- Typechecker context stack depth
266 thisPackage :: PackageId,
269 wayNames :: [WayName], -- way flags from the cmd line
270 buildTag :: String, -- the global "way" (eg. "p" for prof)
271 rtsBuildTag :: String, -- the RTS "way"
274 objectDir :: Maybe String,
275 hiDir :: Maybe String,
276 stubDir :: Maybe String,
282 outputFile :: Maybe String,
283 outputHi :: Maybe String,
285 includePaths :: [String],
286 libraryPaths :: [String],
287 frameworkPaths :: [String], -- used on darwin only
288 cmdlineFrameworks :: [String], -- ditto
289 tmpDir :: String, -- no trailing '/'
291 ghcUsagePath :: FilePath, -- Filled in by SysTools
292 ghciUsagePath :: FilePath, -- ditto
294 hpcDir :: String, -- ^ path to store the .mix files
296 -- options for particular phases
307 -- commands for particular phases
309 pgm_P :: (String,[Option]),
311 pgm_c :: (String,[Option]),
312 pgm_m :: (String,[Option]),
313 pgm_s :: (String,[Option]),
314 pgm_a :: (String,[Option]),
315 pgm_l :: (String,[Option]),
316 pgm_dll :: (String,[Option]),
318 pgm_sysman :: String,
321 extraPkgConfs :: [FilePath],
322 topDir :: FilePath, -- filled in by SysTools
323 systemPackageConfig :: FilePath, -- ditto
324 -- The -package-conf flags given on the command line, in the order
327 packageFlags :: [PackageFlag],
328 -- The -package and -hide-package flags from the command-line
331 -- NB. do not modify this field, it is calculated by
332 -- Packages.initPackages and Packages.updatePackages.
333 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
334 pkgState :: PackageState,
340 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
351 -- | will this target result in an object file on the disk?
352 isObjectTarget :: HscTarget -> Bool
353 isObjectTarget HscC = True
354 isObjectTarget HscAsm = True
355 isObjectTarget _ = False
357 -- | The 'GhcMode' tells us whether we're doing multi-module
358 -- compilation (controlled via the "GHC" API) or one-shot
359 -- (single-module) compilation. This makes a difference primarily to
360 -- the "Finder": in one-shot mode we look for interface files for
361 -- imported modules, but in multi-module mode we look for source files
362 -- in order to check whether they need to be recompiled.
364 = CompManager -- ^ --make, GHCi, etc.
365 | OneShot -- ^ ghc -c Foo.hs
366 | MkDepend -- ^ ghc -M, see Finder for why we need this
369 isOneShot :: GhcMode -> Bool
370 isOneShot OneShot = True
371 isOneShot _other = False
373 -- | What kind of linking to do.
374 data GhcLink -- What to do in the link step, if there is one
375 = NoLink -- Don't link at all
376 | LinkBinary -- Link object code into a binary
377 | LinkInMemory -- Use the in-memory dynamic linker
378 | LinkDynLib -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
381 isNoLink :: GhcLink -> Bool
382 isNoLink NoLink = True
383 isNoLink other = False
386 = ExposePackage String
388 | IgnorePackage String
391 defaultHscTarget = defaultObjectTarget
393 -- | the 'HscTarget' value corresponding to the default way to create
394 -- object files on the current platform.
396 | cGhcWithNativeCodeGen == "YES" = HscAsm
399 initDynFlags dflags = do
400 -- someday these will be dynamic flags
401 ways <- readIORef v_Ways
402 build_tag <- readIORef v_Build_tag
403 rts_build_tag <- readIORef v_RTS_Build_tag
406 buildTag = build_tag,
407 rtsBuildTag = rts_build_tag
412 ghcMode = CompManager,
413 ghcLink = LinkBinary,
416 hscTarget = defaultHscTarget,
421 maxSimplIterations = 4,
425 cmdlineHcIncludes = [],
429 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
431 thisPackage = mainPackageId,
437 objectSuf = phaseInputExt StopLn,
438 hcSuf = phaseInputExt HCc,
441 outputFile = Nothing,
446 cmdlineFrameworks = [],
447 tmpDir = cDEFAULT_TMPDIR,
463 pkgDatabase = Nothing,
464 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
466 Opt_ReadUserPackageConf,
468 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
469 -- behaviour the default, to see if anyone notices
473 Opt_MonomorphismRestriction,
478 Opt_PrintBindResult ]
479 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
480 -- The default -O0 options
483 log_action = \severity srcSpan style msg ->
485 SevInfo -> hPutStrLn stderr (show (msg style))
486 SevFatal -> hPutStrLn stderr (show (msg style))
487 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
493 0 | print errors & warnings only
494 1 | minimal verbosity: print "compiling M ... done." for each module.
495 2 | equivalent to -dshow-passes
496 3 | equivalent to existing "ghc -v"
497 4 | "ghc -v -ddump-most"
498 5 | "ghc -v -ddump-all"
501 dopt :: DynFlag -> DynFlags -> Bool
502 dopt f dflags = f `elem` (flags dflags)
504 dopt_set :: DynFlags -> DynFlag -> DynFlags
505 dopt_set dfs f = dfs{ flags = f : flags dfs }
507 dopt_unset :: DynFlags -> DynFlag -> DynFlags
508 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
510 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
511 getOpts dflags opts = reverse (opts dflags)
512 -- We add to the options from the front, so we need to reverse the list
514 getVerbFlag :: DynFlags -> String
516 | verbosity dflags >= 3 = "-v"
519 setObjectDir f d = d{ objectDir = f}
520 setHiDir f d = d{ hiDir = f}
521 setStubDir f d = d{ stubDir = f}
523 setObjectSuf f d = d{ objectSuf = f}
524 setHiSuf f d = d{ hiSuf = f}
525 setHcSuf f d = d{ hcSuf = f}
527 setOutputFile f d = d{ outputFile = f}
528 setOutputHi f d = d{ outputHi = f}
530 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
531 -- Config.hs should really use Option.
532 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
534 setPgmL f d = d{ pgm_L = f}
535 setPgmF f d = d{ pgm_F = f}
536 setPgmc f d = d{ pgm_c = (f,[])}
537 setPgmm f d = d{ pgm_m = (f,[])}
538 setPgms f d = d{ pgm_s = (f,[])}
539 setPgma f d = d{ pgm_a = (f,[])}
540 setPgml f d = d{ pgm_l = (f,[])}
541 setPgmdll f d = d{ pgm_dll = (f,[])}
543 addOptL f d = d{ opt_L = f : opt_L d}
544 addOptP f d = d{ opt_P = f : opt_P d}
545 addOptF f d = d{ opt_F = f : opt_F d}
546 addOptc f d = d{ opt_c = f : opt_c d}
547 addOptm f d = d{ opt_m = f : opt_m d}
548 addOpta f d = d{ opt_a = f : opt_a d}
549 addOptl f d = d{ opt_l = f : opt_l d}
550 addOptdll f d = d{ opt_dll = f : opt_dll d}
551 addOptdep f d = d{ opt_dep = f : opt_dep d}
553 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
555 -- -----------------------------------------------------------------------------
556 -- Command-line options
558 -- When invoking external tools as part of the compilation pipeline, we
559 -- pass these a sequence of options on the command-line. Rather than
560 -- just using a list of Strings, we use a type that allows us to distinguish
561 -- between filepaths and 'other stuff'. [The reason being, of course, that
562 -- this type gives us a handle on transforming filenames, and filenames only,
563 -- to whatever format they're expected to be on a particular platform.]
566 = FileOption -- an entry that _contains_ filename(s) / filepaths.
567 String -- a non-filepath prefix that shouldn't be
568 -- transformed (e.g., "/out=")
569 String -- the filepath/filename portion
572 -----------------------------------------------------------------------------
573 -- Setting the optimisation level
575 updOptLevel :: Int -> DynFlags -> DynFlags
576 -- Set dynflags appropriate to the optimisation level
578 = dfs2{ optLevel = final_n }
580 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
581 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
582 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
584 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
585 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
587 optLevelFlags :: [([Int], DynFlag)]
589 = [ ([0], Opt_IgnoreInterfacePragmas)
590 , ([0], Opt_OmitInterfacePragmas)
592 , ([1,2], Opt_IgnoreAsserts)
593 , ([1,2], Opt_RewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
595 , ([1,2], Opt_DoEtaReduction)
596 , ([1,2], Opt_CaseMerge)
597 , ([1,2], Opt_Strictness)
599 , ([1,2], Opt_FullLaziness)
601 , ([2], Opt_LiberateCase)
602 , ([2], Opt_SpecConstr)
604 , ([0,1,2], Opt_DoLambdaEtaExpansion)
605 -- This one is important for a tiresome reason:
606 -- we want to make sure that the bindings for data
607 -- constructors are eta-expanded. This is probably
608 -- a good thing anyway, but it seems fragile.
611 -- -----------------------------------------------------------------------------
612 -- Standard sets of warning options
615 = [ Opt_WarnDeprecations,
616 Opt_WarnOverlappingPatterns,
617 Opt_WarnMissingFields,
618 Opt_WarnMissingMethods,
619 Opt_WarnDuplicateExports
623 = standardWarnings ++
624 [ Opt_WarnUnusedBinds,
625 Opt_WarnUnusedMatches,
626 Opt_WarnUnusedImports,
627 Opt_WarnIncompletePatterns,
633 [ Opt_WarnTypeDefaults,
634 Opt_WarnNameShadowing,
640 -- -----------------------------------------------------------------------------
641 -- CoreToDo: abstraction of core-to-core passes to run.
643 data CoreToDo -- These are diff core-to-core passes,
644 -- which may be invoked in any order,
645 -- as many times as you like.
647 = CoreDoSimplify -- The core-to-core simplifier.
650 -- Each run of the simplifier can take a different
651 -- set of simplifier-specific flags.
653 | CoreDoFloatOutwards FloatOutSwitches
658 | CoreDoWorkerWrapper
661 | CoreDoOldStrictness
664 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
665 -- matching this string
666 | CoreDoNothing -- Useful when building up
667 | CoreDoPasses [CoreToDo] -- lists of these things
669 data SimplifierMode -- See comments in SimplMonad
673 data SimplifierSwitch
674 = MaxSimplifierIterations Int
677 data FloatOutSwitches
678 = FloatOutSw Bool -- True <=> float lambdas to top level
679 Bool -- True <=> float constants to top level,
680 -- even if they do not escape a lambda
683 -- The core-to-core pass ordering is derived from the DynFlags:
684 runWhen :: Bool -> CoreToDo -> CoreToDo
685 runWhen True do_this = do_this
686 runWhen False do_this = CoreDoNothing
688 getCoreToDo :: DynFlags -> [CoreToDo]
690 | Just todo <- coreToDo dflags = todo -- set explicitly by user
691 | otherwise = core_todo
693 opt_level = optLevel dflags
694 max_iter = maxSimplIterations dflags
695 strictness = dopt Opt_Strictness dflags
696 full_laziness = dopt Opt_FullLaziness dflags
697 cse = dopt Opt_CSE dflags
698 spec_constr = dopt Opt_SpecConstr dflags
699 liberate_case = dopt Opt_LiberateCase dflags
700 rule_check = ruleCheck dflags
703 if opt_level == 0 then
705 CoreDoSimplify (SimplPhase 0) [
706 MaxSimplifierIterations max_iter
709 else {- opt_level >= 1 -} [
711 -- initial simplify: mk specialiser happy: minimum effort please
712 CoreDoSimplify SimplGently [
714 -- Don't inline anything till full laziness has bitten
715 -- In particular, inlining wrappers inhibits floating
716 -- e.g. ...(case f x of ...)...
717 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
718 -- ==> ...(case x of I# x# -> case fw x# of ...)...
719 -- and now the redex (f x) isn't floatable any more
720 -- Similarly, don't apply any rules until after full
721 -- laziness. Notably, list fusion can prevent floating.
723 NoCaseOfCase, -- Don't do case-of-case transformations.
724 -- This makes full laziness work better
725 MaxSimplifierIterations max_iter
728 -- Specialisation is best done before full laziness
729 -- so that overloaded functions have all their dictionary lambdas manifest
732 runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
736 CoreDoSimplify (SimplPhase 2) [
737 -- Want to run with inline phase 2 after the specialiser to give
738 -- maximum chance for fusion to work before we inline build/augment
739 -- in phase 1. This made a difference in 'ansi' where an
740 -- overloaded function wasn't inlined till too late.
741 MaxSimplifierIterations max_iter
743 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
745 CoreDoSimplify (SimplPhase 1) [
746 -- Need inline-phase2 here so that build/augment get
747 -- inlined. I found that spectral/hartel/genfft lost some useful
748 -- strictness in the function sumcode' if augment is not inlined
749 -- before strictness analysis runs
750 MaxSimplifierIterations max_iter
752 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
754 CoreDoSimplify (SimplPhase 0) [
755 -- Phase 0: allow all Ids to be inlined now
756 -- This gets foldr inlined before strictness analysis
758 MaxSimplifierIterations 3
759 -- At least 3 iterations because otherwise we land up with
760 -- huge dead expressions because of an infelicity in the
762 -- let k = BIG in foldr k z xs
763 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
764 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
768 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
770 #ifdef OLD_STRICTNESS
773 runWhen strictness (CoreDoPasses [
777 CoreDoSimplify (SimplPhase 0) [
778 MaxSimplifierIterations max_iter
781 runWhen full_laziness
782 (CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
783 True)), -- Float constants
784 -- nofib/spectral/hartel/wang doubles in speed if you
785 -- do full laziness late in the day. It only happens
786 -- after fusion and other stuff, so the early pass doesn't
787 -- catch it. For the record, the redex is
788 -- f_el22 (f_el21 r_midblock)
792 -- We want CSE to follow the final full-laziness pass, because it may
793 -- succeed in commoning up things floated out by full laziness.
794 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
798 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
800 -- Case-liberation for -O2. This should be after
801 -- strictness analysis and the simplification which follows it.
802 runWhen liberate_case (CoreDoPasses [
804 CoreDoSimplify (SimplPhase 0) [
805 MaxSimplifierIterations max_iter
806 ] ]), -- Run the simplifier after LiberateCase to vastly
807 -- reduce the possiblility of shadowing
808 -- Reason: see Note [Shadowing] in SpecConstr.lhs
810 runWhen spec_constr CoreDoSpecConstr,
812 -- Final clean-up simplification:
813 CoreDoSimplify (SimplPhase 0) [
814 MaxSimplifierIterations max_iter
818 -- -----------------------------------------------------------------------------
819 -- StgToDo: abstraction of stg-to-stg passes to run.
822 = StgDoMassageForProfiling -- should be (next to) last
823 -- There's also setStgVarInfo, but its absolute "lastness"
824 -- is so critical that it is hardwired in (no flag).
827 getStgToDo :: DynFlags -> [StgToDo]
829 | Just todo <- stgToDo dflags = todo -- set explicitly by user
832 stg_stats = dopt Opt_StgStats dflags
834 todo1 = if stg_stats then [D_stg_stats] else []
836 todo2 | WayProf `elem` wayNames dflags
837 = StgDoMassageForProfiling : todo1
841 -- -----------------------------------------------------------------------------
845 allFlags = map ('-':) $
846 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
847 map ("fno-"++) flags ++
849 where ok (PrefixPred _ _) = False
851 flags = map fst fFlags
853 dynamic_flags :: [(String, OptKind DynP)]
855 ( "n" , NoArg (setDynFlag Opt_DryRun) )
856 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
857 , ( "F" , NoArg (setDynFlag Opt_Pp))
858 , ( "#include" , HasArg (addCmdlineHCInclude) )
859 , ( "v" , OptIntSuffix setVerbosity )
861 ------- Specific phases --------------------------------------------
862 , ( "pgmL" , HasArg (upd . setPgmL) )
863 , ( "pgmP" , HasArg (upd . setPgmP) )
864 , ( "pgmF" , HasArg (upd . setPgmF) )
865 , ( "pgmc" , HasArg (upd . setPgmc) )
866 , ( "pgmm" , HasArg (upd . setPgmm) )
867 , ( "pgms" , HasArg (upd . setPgms) )
868 , ( "pgma" , HasArg (upd . setPgma) )
869 , ( "pgml" , HasArg (upd . setPgml) )
870 , ( "pgmdll" , HasArg (upd . setPgmdll) )
872 , ( "optL" , HasArg (upd . addOptL) )
873 , ( "optP" , HasArg (upd . addOptP) )
874 , ( "optF" , HasArg (upd . addOptF) )
875 , ( "optc" , HasArg (upd . addOptc) )
876 , ( "optm" , HasArg (upd . addOptm) )
877 , ( "opta" , HasArg (upd . addOpta) )
878 , ( "optl" , HasArg (upd . addOptl) )
879 , ( "optdll" , HasArg (upd . addOptdll) )
880 , ( "optdep" , HasArg (upd . addOptdep) )
882 , ( "split-objs" , NoArg (if can_split
883 then setDynFlag Opt_SplitObjs
886 -------- Linking ----------------------------------------------------
887 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
888 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
889 , ( "shared" , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
891 ------- Libraries ---------------------------------------------------
892 , ( "L" , Prefix addLibraryPath )
893 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
896 ------- Frameworks --------------------------------------------------
897 -- -framework-path should really be -F ...
898 , ( "framework-path" , HasArg addFrameworkPath )
899 , ( "framework" , HasArg (upd . addCmdlineFramework) )
901 ------- Output Redirection ------------------------------------------
902 , ( "odir" , HasArg (upd . setObjectDir . Just))
903 , ( "o" , SepArg (upd . setOutputFile . Just))
904 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
905 , ( "osuf" , HasArg (upd . setObjectSuf))
906 , ( "hcsuf" , HasArg (upd . setHcSuf))
907 , ( "hisuf" , HasArg (upd . setHiSuf))
908 , ( "hidir" , HasArg (upd . setHiDir . Just))
909 , ( "tmpdir" , HasArg (upd . setTmpDir))
910 , ( "stubdir" , HasArg (upd . setStubDir . Just))
912 ------- Keeping temporary files -------------------------------------
913 -- These can be singular (think ghc -c) or plural (think ghc --make)
914 , ( "keep-hc-file" , NoArg (setDynFlag Opt_KeepHcFiles))
915 , ( "keep-hc-files" , NoArg (setDynFlag Opt_KeepHcFiles))
916 , ( "keep-s-file" , NoArg (setDynFlag Opt_KeepSFiles))
917 , ( "keep-s-files" , NoArg (setDynFlag Opt_KeepSFiles))
918 , ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
919 , ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
920 -- This only makes sense as plural
921 , ( "keep-tmp-files" , NoArg (setDynFlag Opt_KeepTmpFiles))
923 ------- Miscellaneous ----------------------------------------------
924 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
925 , ( "main-is" , SepArg setMainIs )
926 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
927 , ( "hpcdir" , SepArg setOptHpcDir )
929 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
930 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
931 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
933 ------- Packages ----------------------------------------------------
934 , ( "package-conf" , HasArg extraPkgConf_ )
935 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
936 , ( "package-name" , HasArg (upd . setPackageName) )
937 , ( "package" , HasArg exposePackage )
938 , ( "hide-package" , HasArg hidePackage )
939 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
940 , ( "ignore-package" , HasArg ignorePackage )
941 , ( "syslib" , HasArg exposePackage ) -- for compatibility
943 ------ HsCpp opts ---------------------------------------------------
944 , ( "D", AnySuffix (upd . addOptP) )
945 , ( "U", AnySuffix (upd . addOptP) )
947 ------- Include/Import Paths ----------------------------------------
948 , ( "I" , Prefix addIncludePath)
949 , ( "i" , OptPrefix addImportPath )
951 ------ Debugging ----------------------------------------------------
952 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
954 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
955 , ( "ddump-cps-cmm", setDumpFlag Opt_D_dump_cps_cmm)
956 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
957 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
958 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
959 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
960 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
961 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
962 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
963 , ( "ddump-rule-firings", setDumpFlag Opt_D_dump_rule_firings)
964 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
965 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
966 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
967 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
968 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
969 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
970 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
971 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
972 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
973 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
974 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
975 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
976 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
977 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
978 , ( "ddump-rn-trace", setDumpFlag Opt_D_dump_rn_trace)
979 , ( "ddump-if-trace", setDumpFlag Opt_D_dump_if_trace)
980 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
981 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
982 , ( "ddump-rn-stats", setDumpFlag Opt_D_dump_rn_stats)
983 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
984 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
985 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
986 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
987 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
988 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
989 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
990 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
991 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
992 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
993 , ( "ddump-mod-cycles", setDumpFlag Opt_D_dump_mod_cycles)
995 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
996 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
997 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
998 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
999 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
1000 setVerbosity (Just 2)) )
1001 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
1003 ------ Machine dependant (-m<blah>) stuff ---------------------------
1005 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1006 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1007 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1009 ------ Warning opts -------------------------------------------------
1010 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
1011 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
1012 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
1013 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
1014 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
1016 ------ Optimisation flags ------------------------------------------
1017 , ( "O" , NoArg (upd (setOptLevel 1)))
1018 , ( "Onot" , NoArg (upd (setOptLevel 0)))
1019 , ( "O" , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1020 -- If the number is missing, use 1
1022 , ( "fmax-simplifier-iterations", IntSuffix (\n ->
1023 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1025 -- liberate-case-threshold is an old flag for '-fspec-threshold'
1026 , ( "fspec-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1027 , ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1029 , ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1030 , ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1032 ------ Compiler flags -----------------------------------------------
1034 , ( "fasm", NoArg (setObjTarget HscAsm) )
1035 , ( "fvia-c", NoArg (setObjTarget HscC) )
1036 , ( "fvia-C", NoArg (setObjTarget HscC) )
1038 , ( "fno-code", NoArg (setTarget HscNothing))
1039 , ( "fbyte-code", NoArg (setTarget HscInterpreted) )
1040 , ( "fobject-code", NoArg (setTarget defaultHscTarget) )
1042 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
1043 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1045 -- the rest of the -f* and -fno-* flags
1046 , ( "f", PrefixPred (isFlag fFlags) (\f -> setDynFlag (getFlag fFlags f)) )
1047 , ( "f", PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1049 -- For now, allow -X flags with -f; ToDo: report this as deprecated
1050 , ( "f", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1051 , ( "f", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1053 -- the rest of the -X* and -Xno-* flags
1054 , ( "X", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1055 , ( "X", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1058 -- these -f<blah> flags can all be reversed with -fno-<blah>
1061 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1062 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1063 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude ),
1064 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1065 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1066 ( "warn-missing-fields", Opt_WarnMissingFields ),
1067 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1068 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1069 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1070 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1071 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1072 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1073 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism ),
1074 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1075 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1076 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1077 ( "warn-deprecations", Opt_WarnDeprecations ),
1078 ( "warn-orphans", Opt_WarnOrphans ),
1079 ( "warn-tabs", Opt_WarnTabs ),
1080 ( "strictness", Opt_Strictness ),
1081 ( "full-laziness", Opt_FullLaziness ),
1082 ( "liberate-case", Opt_LiberateCase ),
1083 ( "spec-constr", Opt_SpecConstr ),
1085 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1086 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1087 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1088 ( "ignore-asserts", Opt_IgnoreAsserts ),
1089 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1090 ( "do-eta-reduction", Opt_DoEtaReduction ),
1091 ( "case-merge", Opt_CaseMerge ),
1092 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1093 ( "dicts-cheap", Opt_DictsCheap ),
1094 ( "excess-precision", Opt_ExcessPrecision ),
1095 ( "asm-mangling", Opt_DoAsmMangling ),
1096 ( "print-bind-result", Opt_PrintBindResult ),
1097 ( "force-recomp", Opt_ForceRecomp ),
1098 ( "hpc-no-auto", Opt_Hpc_No_Auto ),
1099 ( "rewrite-rules", Opt_RewriteRules ),
1100 ( "break-on-exception", Opt_BreakOnException ),
1101 ( "vectorise", Opt_Vectorise )
1105 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1106 xFlags :: [(String, DynFlag)]
1109 ( "PatternGuards", Opt_PatternGuards ),
1110 ( "MagicHash", Opt_MagicHash ),
1111 ( "KindSignatures", Opt_KindSignatures ),
1112 ( "EmptyDataDecls", Opt_EmptyDataDecls ),
1113 ( "ParallelListComp", Opt_ParallelListComp ),
1114 ( "FI", Opt_FFI ), -- support `-ffi'...
1115 ( "FFI", Opt_FFI ), -- ...and also `-fffi'
1116 ( "ForeignFunctionInterface", Opt_FFI ),
1118 ( "Rank2Types", Opt_Rank2Types ),
1119 ( "RankNTypes", Opt_RankNTypes ),
1120 ( "RecursiveDo", Opt_RecursiveDo ),
1121 ( "Arrows", Opt_Arrows ), -- arrow syntax
1122 ( "Parr", Opt_PArr ),
1124 ( "TH", Opt_TH ), -- support -fth
1125 ( "TemplateHaskelll", Opt_TH ),
1127 ( "Generics", Opt_Generics ),
1129 ( "ImplicitPrelude", Opt_ImplicitPrelude ), -- On by default
1131 ( "RecordWildCards", Opt_RecordWildCards ),
1132 ( "RecordPuns", Opt_RecordPuns ),
1133 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields ),
1135 ( "OverloadedStrings", Opt_OverloadedStrings ),
1136 ( "GADTs", Opt_GADTs ),
1137 ( "TypeFamilies", Opt_TypeFamilies ),
1138 ( "BangPatterns", Opt_BangPatterns ),
1139 ( "MonomorphismRestriction", Opt_MonomorphismRestriction ), -- On by default
1140 ( "MonoPatBinds", Opt_MonoPatBinds ), -- On by default (which is not strictly H98)
1141 ( "RelaxedPolyRec", Opt_RelaxedPolyRec),
1142 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules ),
1143 ( "ImplicitParams", Opt_ImplicitParams ),
1144 ( "ScopedTypeVariables", Opt_ScopedTypeVariables ),
1145 ( "TypeSynonymInstances", Opt_TypeSynonymInstances ),
1146 ( "FlexibleInstances", Opt_FlexibleInstances ),
1147 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses ),
1148 ( "FunctionalDependencies", Opt_FunctionalDependencies ),
1149 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving ),
1150 ( "AllowOverlappingInstances", Opt_AllowOverlappingInstances ),
1151 ( "AllowUndecidableInstances", Opt_AllowUndecidableInstances ),
1152 ( "AllowIncoherentInstances", Opt_AllowIncoherentInstances )
1155 impliedFlags :: [(DynFlag, [DynFlag])]
1157 ( Opt_GADTs, [Opt_RelaxedPolyRec] ) -- We want type-sig variables to be completely rigid for GADTs
1160 glasgowExtsFlags = [ Opt_GlasgowExts
1163 , Opt_ImplicitParams
1164 , Opt_ScopedTypeVariables
1165 , Opt_TypeSynonymInstances
1166 , Opt_FlexibleInstances
1167 , Opt_MultiParamTypeClasses
1168 , Opt_FunctionalDependencies
1173 , Opt_ParallelListComp
1174 , Opt_EmptyDataDecls
1175 , Opt_KindSignatures
1176 , Opt_GeneralizedNewtypeDeriving
1177 , Opt_TypeFamilies ]
1180 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1182 isFlag flags f = is_flag flags (normaliseFlag f)
1185 | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1188 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1189 -- nf is normalised alreadly
1192 getFlag, getNoFlag :: [(String,a)] -> String -> a
1194 getFlag flags f = get_flag flags (normaliseFlag f)
1196 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1197 -- The flag should be a no-flag already
1199 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1201 [] -> panic ("get_flag " ++ nf)
1204 noFlag_maybe :: String -> Maybe String
1205 -- The input is normalised already
1206 noFlag_maybe ('n' : 'o' : f) = Just f
1207 noFlag_maybe other = Nothing
1209 normaliseFlag :: String -> String
1210 -- Normalise a option flag by
1211 -- * map to lower case
1212 -- * removing hyphens
1213 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1214 normaliseFlag [] = []
1215 normaliseFlag ('-':s) = normaliseFlag s
1216 normaliseFlag (c:s) = toLower c : normaliseFlag s
1218 -- -----------------------------------------------------------------------------
1219 -- Parsing the dynamic flags.
1221 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1222 parseDynamicFlags dflags args = do
1223 let ((leftover,errs),dflags')
1224 = runCmdLine (processArgs dynamic_flags args) dflags
1225 when (not (null errs)) $ do
1226 throwDyn (UsageError (unlines errs))
1227 return (dflags', leftover)
1230 type DynP = CmdLineP DynFlags
1232 upd :: (DynFlags -> DynFlags) -> DynP ()
1234 dfs <- getCmdLineState
1235 putCmdLineState $! (f dfs)
1237 --------------------------
1238 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1239 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1241 deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1242 -- When you set f, set the ones it implies
1243 -- When you un-set f, however, we don't un-set the things it implies
1244 -- (except for -fno-glasgow-exts, which is treated specially)
1246 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1248 --------------------------
1249 setDumpFlag :: DynFlag -> OptKind DynP
1250 setDumpFlag dump_flag
1251 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1252 -- Whenver we -ddump, switch off the recompilation checker,
1253 -- else you don't see the dump!
1255 setVerbosity :: Maybe Int -> DynP ()
1256 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1258 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1260 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1263 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1265 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1267 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1270 | Nothing <- unpackPackageId pid
1271 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1273 = \s -> s{ thisPackage = pid }
1275 pid = stringToPackageId p
1277 -- If we're linking a binary, then only targets that produce object
1278 -- code are allowed (requests for other target types are ignored).
1279 setTarget l = upd set
1282 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
1285 -- Changes the target only if we're compiling object code. This is
1286 -- used by -fasm and -fvia-C, which switch from one to the other, but
1287 -- not from bytecode to object-code. The idea is that -fasm/-fvia-C
1288 -- can be safely used in an OPTIONS_GHC pragma.
1289 setObjTarget l = upd set
1292 | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1295 setOptLevel :: Int -> DynFlags -> DynFlags
1296 setOptLevel n dflags
1297 | hscTarget dflags == HscInterpreted && n > 0
1299 -- not in IO any more, oh well:
1300 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1302 = updOptLevel n dflags
1305 setMainIs :: String -> DynP ()
1307 | not (null main_fn) -- The arg looked like "Foo.baz"
1308 = upd $ \d -> d{ mainFunIs = Just main_fn,
1309 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1311 | isUpper (head main_mod) -- The arg looked like "Foo"
1312 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1314 | otherwise -- The arg looked like "baz"
1315 = upd $ \d -> d{ mainFunIs = Just main_mod }
1317 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1319 -----------------------------------------------------------------------------
1320 -- Paths & Libraries
1322 -- -i on its own deletes the import paths
1323 addImportPath "" = upd (\s -> s{importPaths = []})
1324 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1328 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1331 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1333 addFrameworkPath p =
1334 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1336 split_marker = ':' -- not configurable (ToDo)
1338 splitPathList :: String -> [String]
1339 splitPathList s = filter notNull (splitUp s)
1340 -- empty paths are ignored: there might be a trailing
1341 -- ':' in the initial list, for example. Empty paths can
1342 -- cause confusion when they are translated into -I options
1343 -- for passing to gcc.
1345 #ifndef mingw32_TARGET_OS
1346 splitUp xs = split split_marker xs
1348 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1350 -- That is, if "foo:bar:baz" is used, this interpreted as
1351 -- consisting of three entries, 'foo', 'bar', 'baz'.
1352 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1353 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1355 -- Notice that no attempt is made to fully replace the 'standard'
1356 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1357 -- that this will cause too much breakage for users & ':' will
1358 -- work fine even with DOS paths, if you're not insisting on being silly.
1361 splitUp (x:':':div:xs) | div `elem` dir_markers
1362 = ((x:':':div:p): splitUp rs)
1364 (p,rs) = findNextPath xs
1365 -- we used to check for existence of the path here, but that
1366 -- required the IO monad to be threaded through the command-line
1367 -- parser which is quite inconvenient. The
1368 splitUp xs = cons p (splitUp rs)
1370 (p,rs) = findNextPath xs
1375 -- will be called either when we've consumed nought or the
1376 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1377 -- finding the next split marker.
1379 case break (`elem` split_markers) xs of
1380 (p, d:ds) -> (p, ds)
1383 split_markers :: [Char]
1384 split_markers = [':', ';']
1386 dir_markers :: [Char]
1387 dir_markers = ['/', '\\']
1390 -- -----------------------------------------------------------------------------
1391 -- tmpDir, where we store temporary files.
1393 setTmpDir :: FilePath -> DynFlags -> DynFlags
1394 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1396 #if !defined(mingw32_HOST_OS)
1397 canonicalise p = normalisePath p
1399 -- Canonicalisation of temp path under win32 is a bit more
1400 -- involved: (a) strip trailing slash,
1401 -- (b) normalise slashes
1402 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1404 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1406 -- if we're operating under cygwin, and TMP/TEMP is of
1407 -- the form "/cygdrive/drive/path", translate this to
1408 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1409 -- understand /cygdrive paths.)
1411 | "/cygdrive/" `isPrefixOf` path =
1412 case drop (length "/cygdrive/") path of
1413 drive:xs@('/':_) -> drive:':':xs
1417 -- strip the trailing backslash (awful, but we only do this once).
1418 removeTrailingSlash path =
1425 -----------------------------------------------------------------------------
1428 setOptHpcDir :: String -> DynP ()
1429 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1431 -----------------------------------------------------------------------------
1432 -- Via-C compilation stuff
1434 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1435 [String]) -- for registerised HC compilations
1436 machdepCCOpts dflags
1437 #if alpha_TARGET_ARCH
1439 #ifdef HAVE_THREADED_RTS_SUPPORT
1443 -- For now, to suppress the gcc warning "call-clobbered
1444 -- register used for global register variable", we simply
1445 -- disable all warnings altogether using the -w flag. Oh well.
1447 #elif hppa_TARGET_ARCH
1448 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1449 -- (very nice, but too bad the HP /usr/include files don't agree.)
1450 = ( ["-D_HPUX_SOURCE"], [] )
1452 #elif m68k_TARGET_ARCH
1453 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1454 -- popping of args to routines to be explicit; if we let things
1455 -- be deferred 'til after an STGJUMP, imminent death is certain!
1457 -- -fomit-frame-pointer : *don't*
1458 -- It's better to have a6 completely tied up being a frame pointer
1459 -- rather than let GCC pick random things to do with it.
1460 -- (If we want to steal a6, then we would try to do things
1461 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1462 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1464 #elif i386_TARGET_ARCH
1465 -- -fno-defer-pop : basically the same game as for m68k
1467 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1468 -- the fp (%ebp) for our register maps.
1469 = let n_regs = stolen_x86_regs dflags
1472 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1473 -- , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else ""
1476 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1477 -- Some gccs are configured with
1478 -- -momit-leaf-frame-pointer on by default, and it
1479 -- apparently takes precedence over
1480 -- -fomit-frame-pointer, so we disable it first here.
1481 "-mno-omit-leaf-frame-pointer",
1483 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1484 "-fno-unit-at-a-time",
1485 -- unit-at-a-time doesn't do us any good, and screws
1486 -- up -split-objs by moving the split markers around.
1487 -- It's only turned on with -O2, but put it here just
1488 -- in case someone uses -optc-O2.
1490 "-fomit-frame-pointer",
1491 -- we want -fno-builtin, because when gcc inlines
1492 -- built-in functions like memcpy() it tends to
1493 -- run out of registers, requiring -monly-n-regs
1495 "-DSTOLEN_X86_REGS="++show n_regs ]
1498 #elif ia64_TARGET_ARCH
1499 = ( [], ["-fomit-frame-pointer", "-G0"] )
1501 #elif x86_64_TARGET_ARCH
1502 = ( [], ["-fomit-frame-pointer",
1503 "-fno-asynchronous-unwind-tables",
1504 -- the unwind tables are unnecessary for HC code,
1505 -- and get in the way of -split-objs. Another option
1506 -- would be to throw them away in the mangler, but this
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.
1516 -- calling builtins like strlen() using the FFI can
1517 -- cause gcc to run out of regs, so use the external
1521 #elif sparc_TARGET_ARCH
1523 -- For now, to suppress the gcc warning "call-clobbered
1524 -- register used for global register variable", we simply
1525 -- disable all warnings altogether using the -w flag. Oh well.
1527 #elif powerpc_apple_darwin_TARGET
1529 -- Disable Apple's precompiling preprocessor. It's a great thing
1530 -- for "normal" programs, but it doesn't support register variable
1532 = ( [], ["-no-cpp-precomp"] )
1537 picCCOpts :: DynFlags -> [String]
1539 #if darwin_TARGET_OS
1540 -- Apple prefers to do things the other way round.
1541 -- PIC is on by default.
1542 -- -mdynamic-no-pic:
1543 -- Turn off PIC code generation.
1545 -- Don't generate "common" symbols - these are unwanted
1546 -- in dynamic libraries.
1551 = ["-mdynamic-no-pic"]
1552 #elif mingw32_TARGET_OS
1553 -- no -fPIC for Windows
1562 -- -----------------------------------------------------------------------------
1567 #if defined(i386_TARGET_ARCH) \
1568 || defined(x86_64_TARGET_ARCH) \
1569 || defined(alpha_TARGET_ARCH) \
1570 || defined(hppa_TARGET_ARCH) \
1571 || defined(m68k_TARGET_ARCH) \
1572 || defined(mips_TARGET_ARCH) \
1573 || defined(powerpc_TARGET_ARCH) \
1574 || defined(rs6000_TARGET_ARCH) \
1575 || defined(sparc_TARGET_ARCH)