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
194 | Opt_ParallelListComp
195 | Opt_GeneralizedNewtypeDeriving
207 | Opt_IgnoreInterfacePragmas
208 | Opt_OmitInterfacePragmas
209 | Opt_DoLambdaEtaExpansion
211 | Opt_IgnoreBreakpoints
214 | Opt_UnboxStrictFields
225 | Opt_ExcessPrecision
226 | Opt_ReadUserPackageConf
230 | Opt_HideAllPackages
231 | Opt_PrintBindResult
234 | Opt_BreakOnException
245 data DynFlags = DynFlags {
248 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
249 stgToDo :: Maybe [StgToDo], -- similarly
250 hscTarget :: HscTarget,
251 hscOutName :: String, -- name of the output file
252 extCoreName :: String, -- name of the .core output file
253 verbosity :: Int, -- verbosity level
254 optLevel :: Int, -- optimisation level
255 maxSimplIterations :: Int, -- max simplifier iterations
256 ruleCheck :: Maybe String,
258 specThreshold :: Int, -- Threshold for function specialisation
260 stolen_x86_regs :: Int,
261 cmdlineHcIncludes :: [String], -- -#includes
262 importPaths :: [FilePath],
264 mainFunIs :: Maybe String,
265 ctxtStkDepth :: Int, -- Typechecker context stack depth
267 thisPackage :: PackageId,
270 wayNames :: [WayName], -- way flags from the cmd line
271 buildTag :: String, -- the global "way" (eg. "p" for prof)
272 rtsBuildTag :: String, -- the RTS "way"
275 objectDir :: Maybe String,
276 hiDir :: Maybe String,
277 stubDir :: Maybe String,
283 outputFile :: Maybe String,
284 outputHi :: Maybe String,
286 includePaths :: [String],
287 libraryPaths :: [String],
288 frameworkPaths :: [String], -- used on darwin only
289 cmdlineFrameworks :: [String], -- ditto
290 tmpDir :: String, -- no trailing '/'
292 ghcUsagePath :: FilePath, -- Filled in by SysTools
293 ghciUsagePath :: FilePath, -- ditto
295 hpcDir :: String, -- ^ path to store the .mix files
297 -- options for particular phases
308 -- commands for particular phases
310 pgm_P :: (String,[Option]),
312 pgm_c :: (String,[Option]),
313 pgm_m :: (String,[Option]),
314 pgm_s :: (String,[Option]),
315 pgm_a :: (String,[Option]),
316 pgm_l :: (String,[Option]),
317 pgm_dll :: (String,[Option]),
319 pgm_sysman :: String,
322 extraPkgConfs :: [FilePath],
323 topDir :: FilePath, -- filled in by SysTools
324 systemPackageConfig :: FilePath, -- ditto
325 -- The -package-conf flags given on the command line, in the order
328 packageFlags :: [PackageFlag],
329 -- The -package and -hide-package flags from the command-line
332 -- NB. do not modify this field, it is calculated by
333 -- Packages.initPackages and Packages.updatePackages.
334 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
335 pkgState :: PackageState,
341 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
352 -- | will this target result in an object file on the disk?
353 isObjectTarget :: HscTarget -> Bool
354 isObjectTarget HscC = True
355 isObjectTarget HscAsm = True
356 isObjectTarget _ = False
358 -- | The 'GhcMode' tells us whether we're doing multi-module
359 -- compilation (controlled via the "GHC" API) or one-shot
360 -- (single-module) compilation. This makes a difference primarily to
361 -- the "Finder": in one-shot mode we look for interface files for
362 -- imported modules, but in multi-module mode we look for source files
363 -- in order to check whether they need to be recompiled.
365 = CompManager -- ^ --make, GHCi, etc.
366 | OneShot -- ^ ghc -c Foo.hs
367 | MkDepend -- ^ ghc -M, see Finder for why we need this
370 isOneShot :: GhcMode -> Bool
371 isOneShot OneShot = True
372 isOneShot _other = False
374 -- | What kind of linking to do.
375 data GhcLink -- What to do in the link step, if there is one
376 = NoLink -- Don't link at all
377 | LinkBinary -- Link object code into a binary
378 | LinkInMemory -- Use the in-memory dynamic linker
379 | LinkDynLib -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
382 isNoLink :: GhcLink -> Bool
383 isNoLink NoLink = True
384 isNoLink other = False
387 = ExposePackage String
389 | IgnorePackage String
392 defaultHscTarget = defaultObjectTarget
394 -- | the 'HscTarget' value corresponding to the default way to create
395 -- object files on the current platform.
397 | cGhcWithNativeCodeGen == "YES" = HscAsm
400 initDynFlags dflags = do
401 -- someday these will be dynamic flags
402 ways <- readIORef v_Ways
403 build_tag <- readIORef v_Build_tag
404 rts_build_tag <- readIORef v_RTS_Build_tag
407 buildTag = build_tag,
408 rtsBuildTag = rts_build_tag
413 ghcMode = CompManager,
414 ghcLink = LinkBinary,
417 hscTarget = defaultHscTarget,
422 maxSimplIterations = 4,
426 cmdlineHcIncludes = [],
430 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
432 thisPackage = mainPackageId,
438 objectSuf = phaseInputExt StopLn,
439 hcSuf = phaseInputExt HCc,
442 outputFile = Nothing,
447 cmdlineFrameworks = [],
448 tmpDir = cDEFAULT_TMPDIR,
464 pkgDatabase = Nothing,
465 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
467 Opt_ReadUserPackageConf,
469 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
470 -- behaviour the default, to see if anyone notices
474 Opt_MonomorphismRestriction,
479 Opt_PrintBindResult ]
480 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
481 -- The default -O0 options
484 log_action = \severity srcSpan style msg ->
486 SevInfo -> hPutStrLn stderr (show (msg style))
487 SevFatal -> hPutStrLn stderr (show (msg style))
488 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
494 0 | print errors & warnings only
495 1 | minimal verbosity: print "compiling M ... done." for each module.
496 2 | equivalent to -dshow-passes
497 3 | equivalent to existing "ghc -v"
498 4 | "ghc -v -ddump-most"
499 5 | "ghc -v -ddump-all"
502 dopt :: DynFlag -> DynFlags -> Bool
503 dopt f dflags = f `elem` (flags dflags)
505 dopt_set :: DynFlags -> DynFlag -> DynFlags
506 dopt_set dfs f = dfs{ flags = f : flags dfs }
508 dopt_unset :: DynFlags -> DynFlag -> DynFlags
509 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
511 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
512 getOpts dflags opts = reverse (opts dflags)
513 -- We add to the options from the front, so we need to reverse the list
515 getVerbFlag :: DynFlags -> String
517 | verbosity dflags >= 3 = "-v"
520 setObjectDir f d = d{ objectDir = f}
521 setHiDir f d = d{ hiDir = f}
522 setStubDir f d = d{ stubDir = f}
524 setObjectSuf f d = d{ objectSuf = f}
525 setHiSuf f d = d{ hiSuf = f}
526 setHcSuf f d = d{ hcSuf = f}
528 setOutputFile f d = d{ outputFile = f}
529 setOutputHi f d = d{ outputHi = f}
531 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
532 -- Config.hs should really use Option.
533 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
535 setPgmL f d = d{ pgm_L = f}
536 setPgmF f d = d{ pgm_F = f}
537 setPgmc f d = d{ pgm_c = (f,[])}
538 setPgmm f d = d{ pgm_m = (f,[])}
539 setPgms f d = d{ pgm_s = (f,[])}
540 setPgma f d = d{ pgm_a = (f,[])}
541 setPgml f d = d{ pgm_l = (f,[])}
542 setPgmdll f d = d{ pgm_dll = (f,[])}
544 addOptL f d = d{ opt_L = f : opt_L d}
545 addOptP f d = d{ opt_P = f : opt_P d}
546 addOptF f d = d{ opt_F = f : opt_F d}
547 addOptc f d = d{ opt_c = f : opt_c d}
548 addOptm f d = d{ opt_m = f : opt_m d}
549 addOpta f d = d{ opt_a = f : opt_a d}
550 addOptl f d = d{ opt_l = f : opt_l d}
551 addOptdll f d = d{ opt_dll = f : opt_dll d}
552 addOptdep f d = d{ opt_dep = f : opt_dep d}
554 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
556 -- -----------------------------------------------------------------------------
557 -- Command-line options
559 -- When invoking external tools as part of the compilation pipeline, we
560 -- pass these a sequence of options on the command-line. Rather than
561 -- just using a list of Strings, we use a type that allows us to distinguish
562 -- between filepaths and 'other stuff'. [The reason being, of course, that
563 -- this type gives us a handle on transforming filenames, and filenames only,
564 -- to whatever format they're expected to be on a particular platform.]
567 = FileOption -- an entry that _contains_ filename(s) / filepaths.
568 String -- a non-filepath prefix that shouldn't be
569 -- transformed (e.g., "/out=")
570 String -- the filepath/filename portion
573 -----------------------------------------------------------------------------
574 -- Setting the optimisation level
576 updOptLevel :: Int -> DynFlags -> DynFlags
577 -- Set dynflags appropriate to the optimisation level
579 = dfs2{ optLevel = final_n }
581 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
582 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
583 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
585 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
586 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
588 optLevelFlags :: [([Int], DynFlag)]
590 = [ ([0], Opt_IgnoreInterfacePragmas)
591 , ([0], Opt_OmitInterfacePragmas)
593 , ([1,2], Opt_IgnoreAsserts)
594 , ([1,2], Opt_RewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
596 , ([1,2], Opt_DoEtaReduction)
597 , ([1,2], Opt_CaseMerge)
598 , ([1,2], Opt_Strictness)
600 , ([1,2], Opt_FullLaziness)
602 , ([2], Opt_LiberateCase)
603 , ([2], Opt_SpecConstr)
605 , ([0,1,2], Opt_DoLambdaEtaExpansion)
606 -- This one is important for a tiresome reason:
607 -- we want to make sure that the bindings for data
608 -- constructors are eta-expanded. This is probably
609 -- a good thing anyway, but it seems fragile.
612 -- -----------------------------------------------------------------------------
613 -- Standard sets of warning options
616 = [ Opt_WarnDeprecations,
617 Opt_WarnOverlappingPatterns,
618 Opt_WarnMissingFields,
619 Opt_WarnMissingMethods,
620 Opt_WarnDuplicateExports
624 = standardWarnings ++
625 [ Opt_WarnUnusedBinds,
626 Opt_WarnUnusedMatches,
627 Opt_WarnUnusedImports,
628 Opt_WarnIncompletePatterns,
634 [ Opt_WarnTypeDefaults,
635 Opt_WarnNameShadowing,
641 -- -----------------------------------------------------------------------------
642 -- CoreToDo: abstraction of core-to-core passes to run.
644 data CoreToDo -- These are diff core-to-core passes,
645 -- which may be invoked in any order,
646 -- as many times as you like.
648 = CoreDoSimplify -- The core-to-core simplifier.
651 -- Each run of the simplifier can take a different
652 -- set of simplifier-specific flags.
654 | CoreDoFloatOutwards FloatOutSwitches
659 | CoreDoWorkerWrapper
662 | CoreDoOldStrictness
665 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
666 -- matching this string
667 | CoreDoNothing -- Useful when building up
668 | CoreDoPasses [CoreToDo] -- lists of these things
670 data SimplifierMode -- See comments in SimplMonad
674 data SimplifierSwitch
675 = MaxSimplifierIterations Int
678 data FloatOutSwitches
679 = FloatOutSw Bool -- True <=> float lambdas to top level
680 Bool -- True <=> float constants to top level,
681 -- even if they do not escape a lambda
684 -- The core-to-core pass ordering is derived from the DynFlags:
685 runWhen :: Bool -> CoreToDo -> CoreToDo
686 runWhen True do_this = do_this
687 runWhen False do_this = CoreDoNothing
689 getCoreToDo :: DynFlags -> [CoreToDo]
691 | Just todo <- coreToDo dflags = todo -- set explicitly by user
692 | otherwise = core_todo
694 opt_level = optLevel dflags
695 max_iter = maxSimplIterations dflags
696 strictness = dopt Opt_Strictness dflags
697 full_laziness = dopt Opt_FullLaziness dflags
698 cse = dopt Opt_CSE dflags
699 spec_constr = dopt Opt_SpecConstr dflags
700 liberate_case = dopt Opt_LiberateCase dflags
701 rule_check = ruleCheck dflags
704 if opt_level == 0 then
706 CoreDoSimplify (SimplPhase 0) [
707 MaxSimplifierIterations max_iter
710 else {- opt_level >= 1 -} [
712 -- initial simplify: mk specialiser happy: minimum effort please
713 CoreDoSimplify SimplGently [
715 -- Don't inline anything till full laziness has bitten
716 -- In particular, inlining wrappers inhibits floating
717 -- e.g. ...(case f x of ...)...
718 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
719 -- ==> ...(case x of I# x# -> case fw x# of ...)...
720 -- and now the redex (f x) isn't floatable any more
721 -- Similarly, don't apply any rules until after full
722 -- laziness. Notably, list fusion can prevent floating.
724 NoCaseOfCase, -- Don't do case-of-case transformations.
725 -- This makes full laziness work better
726 MaxSimplifierIterations max_iter
729 -- Specialisation is best done before full laziness
730 -- so that overloaded functions have all their dictionary lambdas manifest
733 runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
737 CoreDoSimplify (SimplPhase 2) [
738 -- Want to run with inline phase 2 after the specialiser to give
739 -- maximum chance for fusion to work before we inline build/augment
740 -- in phase 1. This made a difference in 'ansi' where an
741 -- overloaded function wasn't inlined till too late.
742 MaxSimplifierIterations max_iter
744 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
746 CoreDoSimplify (SimplPhase 1) [
747 -- Need inline-phase2 here so that build/augment get
748 -- inlined. I found that spectral/hartel/genfft lost some useful
749 -- strictness in the function sumcode' if augment is not inlined
750 -- before strictness analysis runs
751 MaxSimplifierIterations max_iter
753 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
755 CoreDoSimplify (SimplPhase 0) [
756 -- Phase 0: allow all Ids to be inlined now
757 -- This gets foldr inlined before strictness analysis
759 MaxSimplifierIterations 3
760 -- At least 3 iterations because otherwise we land up with
761 -- huge dead expressions because of an infelicity in the
763 -- let k = BIG in foldr k z xs
764 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
765 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
769 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
771 #ifdef OLD_STRICTNESS
774 runWhen strictness (CoreDoPasses [
778 CoreDoSimplify (SimplPhase 0) [
779 MaxSimplifierIterations max_iter
782 runWhen full_laziness
783 (CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
784 True)), -- Float constants
785 -- nofib/spectral/hartel/wang doubles in speed if you
786 -- do full laziness late in the day. It only happens
787 -- after fusion and other stuff, so the early pass doesn't
788 -- catch it. For the record, the redex is
789 -- f_el22 (f_el21 r_midblock)
793 -- We want CSE to follow the final full-laziness pass, because it may
794 -- succeed in commoning up things floated out by full laziness.
795 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
799 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
801 -- Case-liberation for -O2. This should be after
802 -- strictness analysis and the simplification which follows it.
803 runWhen liberate_case (CoreDoPasses [
805 CoreDoSimplify (SimplPhase 0) [
806 MaxSimplifierIterations max_iter
807 ] ]), -- Run the simplifier after LiberateCase to vastly
808 -- reduce the possiblility of shadowing
809 -- Reason: see Note [Shadowing] in SpecConstr.lhs
811 runWhen spec_constr CoreDoSpecConstr,
813 -- Final clean-up simplification:
814 CoreDoSimplify (SimplPhase 0) [
815 MaxSimplifierIterations max_iter
819 -- -----------------------------------------------------------------------------
820 -- StgToDo: abstraction of stg-to-stg passes to run.
823 = StgDoMassageForProfiling -- should be (next to) last
824 -- There's also setStgVarInfo, but its absolute "lastness"
825 -- is so critical that it is hardwired in (no flag).
828 getStgToDo :: DynFlags -> [StgToDo]
830 | Just todo <- stgToDo dflags = todo -- set explicitly by user
833 stg_stats = dopt Opt_StgStats dflags
835 todo1 = if stg_stats then [D_stg_stats] else []
837 todo2 | WayProf `elem` wayNames dflags
838 = StgDoMassageForProfiling : todo1
842 -- -----------------------------------------------------------------------------
846 allFlags = map ('-':) $
847 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
848 map ("fno-"++) flags ++
850 where ok (PrefixPred _ _) = False
852 flags = map fst fFlags
854 dynamic_flags :: [(String, OptKind DynP)]
856 ( "n" , NoArg (setDynFlag Opt_DryRun) )
857 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
858 , ( "F" , NoArg (setDynFlag Opt_Pp))
859 , ( "#include" , HasArg (addCmdlineHCInclude) )
860 , ( "v" , OptIntSuffix setVerbosity )
862 ------- Specific phases --------------------------------------------
863 , ( "pgmL" , HasArg (upd . setPgmL) )
864 , ( "pgmP" , HasArg (upd . setPgmP) )
865 , ( "pgmF" , HasArg (upd . setPgmF) )
866 , ( "pgmc" , HasArg (upd . setPgmc) )
867 , ( "pgmm" , HasArg (upd . setPgmm) )
868 , ( "pgms" , HasArg (upd . setPgms) )
869 , ( "pgma" , HasArg (upd . setPgma) )
870 , ( "pgml" , HasArg (upd . setPgml) )
871 , ( "pgmdll" , HasArg (upd . setPgmdll) )
873 , ( "optL" , HasArg (upd . addOptL) )
874 , ( "optP" , HasArg (upd . addOptP) )
875 , ( "optF" , HasArg (upd . addOptF) )
876 , ( "optc" , HasArg (upd . addOptc) )
877 , ( "optm" , HasArg (upd . addOptm) )
878 , ( "opta" , HasArg (upd . addOpta) )
879 , ( "optl" , HasArg (upd . addOptl) )
880 , ( "optdll" , HasArg (upd . addOptdll) )
881 , ( "optdep" , HasArg (upd . addOptdep) )
883 , ( "split-objs" , NoArg (if can_split
884 then setDynFlag Opt_SplitObjs
887 -------- Linking ----------------------------------------------------
888 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
889 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
890 , ( "shared" , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
892 ------- Libraries ---------------------------------------------------
893 , ( "L" , Prefix addLibraryPath )
894 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
897 ------- Frameworks --------------------------------------------------
898 -- -framework-path should really be -F ...
899 , ( "framework-path" , HasArg addFrameworkPath )
900 , ( "framework" , HasArg (upd . addCmdlineFramework) )
902 ------- Output Redirection ------------------------------------------
903 , ( "odir" , HasArg (upd . setObjectDir . Just))
904 , ( "o" , SepArg (upd . setOutputFile . Just))
905 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
906 , ( "osuf" , HasArg (upd . setObjectSuf))
907 , ( "hcsuf" , HasArg (upd . setHcSuf))
908 , ( "hisuf" , HasArg (upd . setHiSuf))
909 , ( "hidir" , HasArg (upd . setHiDir . Just))
910 , ( "tmpdir" , HasArg (upd . setTmpDir))
911 , ( "stubdir" , HasArg (upd . setStubDir . Just))
913 ------- Keeping temporary files -------------------------------------
914 -- These can be singular (think ghc -c) or plural (think ghc --make)
915 , ( "keep-hc-file" , NoArg (setDynFlag Opt_KeepHcFiles))
916 , ( "keep-hc-files" , NoArg (setDynFlag Opt_KeepHcFiles))
917 , ( "keep-s-file" , NoArg (setDynFlag Opt_KeepSFiles))
918 , ( "keep-s-files" , NoArg (setDynFlag Opt_KeepSFiles))
919 , ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
920 , ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
921 -- This only makes sense as plural
922 , ( "keep-tmp-files" , NoArg (setDynFlag Opt_KeepTmpFiles))
924 ------- Miscellaneous ----------------------------------------------
925 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
926 , ( "main-is" , SepArg setMainIs )
927 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
928 , ( "hpcdir" , SepArg setOptHpcDir )
930 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
931 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
932 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
934 ------- Packages ----------------------------------------------------
935 , ( "package-conf" , HasArg extraPkgConf_ )
936 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
937 , ( "package-name" , HasArg (upd . setPackageName) )
938 , ( "package" , HasArg exposePackage )
939 , ( "hide-package" , HasArg hidePackage )
940 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
941 , ( "ignore-package" , HasArg ignorePackage )
942 , ( "syslib" , HasArg exposePackage ) -- for compatibility
944 ------ HsCpp opts ---------------------------------------------------
945 , ( "D", AnySuffix (upd . addOptP) )
946 , ( "U", AnySuffix (upd . addOptP) )
948 ------- Include/Import Paths ----------------------------------------
949 , ( "I" , Prefix addIncludePath)
950 , ( "i" , OptPrefix addImportPath )
952 ------ Debugging ----------------------------------------------------
953 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
955 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
956 , ( "ddump-cps-cmm", setDumpFlag Opt_D_dump_cps_cmm)
957 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
958 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
959 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
960 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
961 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
962 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
963 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
964 , ( "ddump-rule-firings", setDumpFlag Opt_D_dump_rule_firings)
965 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
966 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
967 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
968 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
969 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
970 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
971 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
972 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
973 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
974 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
975 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
976 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
977 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
978 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
979 , ( "ddump-rn-trace", setDumpFlag Opt_D_dump_rn_trace)
980 , ( "ddump-if-trace", setDumpFlag Opt_D_dump_if_trace)
981 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
982 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
983 , ( "ddump-rn-stats", setDumpFlag Opt_D_dump_rn_stats)
984 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
985 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
986 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
987 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
988 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
989 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
990 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
991 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
992 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
993 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
994 , ( "ddump-mod-cycles", setDumpFlag Opt_D_dump_mod_cycles)
996 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
997 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
998 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
999 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
1000 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
1001 setVerbosity (Just 2)) )
1002 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
1004 ------ Machine dependant (-m<blah>) stuff ---------------------------
1006 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1007 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1008 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1010 ------ Warning opts -------------------------------------------------
1011 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
1012 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
1013 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
1014 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
1015 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
1017 ------ Optimisation flags ------------------------------------------
1018 , ( "O" , NoArg (upd (setOptLevel 1)))
1019 , ( "Onot" , NoArg (upd (setOptLevel 0)))
1020 , ( "O" , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1021 -- If the number is missing, use 1
1023 , ( "fmax-simplifier-iterations", IntSuffix (\n ->
1024 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1026 -- liberate-case-threshold is an old flag for '-fspec-threshold'
1027 , ( "fspec-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1028 , ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1030 , ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1031 , ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1033 ------ Compiler flags -----------------------------------------------
1035 , ( "fasm", NoArg (setObjTarget HscAsm) )
1036 , ( "fvia-c", NoArg (setObjTarget HscC) )
1037 , ( "fvia-C", NoArg (setObjTarget HscC) )
1039 , ( "fno-code", NoArg (setTarget HscNothing))
1040 , ( "fbyte-code", NoArg (setTarget HscInterpreted) )
1041 , ( "fobject-code", NoArg (setTarget defaultHscTarget) )
1043 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
1044 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1046 -- the rest of the -f* and -fno-* flags
1047 , ( "f", PrefixPred (isFlag fFlags) (\f -> setDynFlag (getFlag fFlags f)) )
1048 , ( "f", PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1050 -- For now, allow -X flags with -f; ToDo: report this as deprecated
1051 , ( "f", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1052 , ( "f", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1054 -- the rest of the -X* and -Xno-* flags
1055 , ( "X", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1056 , ( "X", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1059 -- these -f<blah> flags can all be reversed with -fno-<blah>
1062 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1063 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1064 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude ),
1065 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1066 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1067 ( "warn-missing-fields", Opt_WarnMissingFields ),
1068 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1069 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1070 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1071 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1072 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1073 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1074 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism ),
1075 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1076 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1077 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1078 ( "warn-deprecations", Opt_WarnDeprecations ),
1079 ( "warn-orphans", Opt_WarnOrphans ),
1080 ( "warn-tabs", Opt_WarnTabs ),
1081 ( "strictness", Opt_Strictness ),
1082 ( "full-laziness", Opt_FullLaziness ),
1083 ( "liberate-case", Opt_LiberateCase ),
1084 ( "spec-constr", Opt_SpecConstr ),
1086 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1087 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1088 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1089 ( "ignore-asserts", Opt_IgnoreAsserts ),
1090 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1091 ( "do-eta-reduction", Opt_DoEtaReduction ),
1092 ( "case-merge", Opt_CaseMerge ),
1093 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1094 ( "dicts-cheap", Opt_DictsCheap ),
1095 ( "excess-precision", Opt_ExcessPrecision ),
1096 ( "asm-mangling", Opt_DoAsmMangling ),
1097 ( "print-bind-result", Opt_PrintBindResult ),
1098 ( "force-recomp", Opt_ForceRecomp ),
1099 ( "hpc-no-auto", Opt_Hpc_No_Auto ),
1100 ( "rewrite-rules", Opt_RewriteRules ),
1101 ( "break-on-exception", Opt_BreakOnException ),
1102 ( "vectorise", Opt_Vectorise )
1106 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1107 xFlags :: [(String, DynFlag)]
1110 ( "PatternGuards", Opt_PatternGuards ),
1111 ( "UnicodeSyntax", Opt_UnicodeSyntax ),
1112 ( "MagicHash", Opt_MagicHash ),
1113 ( "KindSignatures", Opt_KindSignatures ),
1114 ( "EmptyDataDecls", Opt_EmptyDataDecls ),
1115 ( "ParallelListComp", Opt_ParallelListComp ),
1116 ( "FI", Opt_FFI ), -- support `-ffi'...
1117 ( "FFI", Opt_FFI ), -- ...and also `-fffi'
1118 ( "ForeignFunctionInterface", Opt_FFI ),
1120 ( "Rank2Types", Opt_Rank2Types ),
1121 ( "RankNTypes", Opt_RankNTypes ),
1122 ( "RecursiveDo", Opt_RecursiveDo ),
1123 ( "Arrows", Opt_Arrows ), -- arrow syntax
1124 ( "Parr", Opt_PArr ),
1126 ( "TH", Opt_TH ), -- support -fth
1127 ( "TemplateHaskelll", Opt_TH ),
1129 ( "Generics", Opt_Generics ),
1131 ( "ImplicitPrelude", Opt_ImplicitPrelude ), -- On by default
1133 ( "RecordWildCards", Opt_RecordWildCards ),
1134 ( "RecordPuns", Opt_RecordPuns ),
1135 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields ),
1137 ( "OverloadedStrings", Opt_OverloadedStrings ),
1138 ( "GADTs", Opt_GADTs ),
1139 ( "TypeFamilies", Opt_TypeFamilies ),
1140 ( "BangPatterns", Opt_BangPatterns ),
1141 ( "MonomorphismRestriction", Opt_MonomorphismRestriction ), -- On by default
1142 ( "MonoPatBinds", Opt_MonoPatBinds ), -- On by default (which is not strictly H98)
1143 ( "RelaxedPolyRec", Opt_RelaxedPolyRec),
1144 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules ),
1145 ( "ImplicitParams", Opt_ImplicitParams ),
1146 ( "ScopedTypeVariables", Opt_ScopedTypeVariables ),
1147 ( "TypeSynonymInstances", Opt_TypeSynonymInstances ),
1148 ( "FlexibleInstances", Opt_FlexibleInstances ),
1149 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses ),
1150 ( "FunctionalDependencies", Opt_FunctionalDependencies ),
1151 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving ),
1152 ( "AllowOverlappingInstances", Opt_AllowOverlappingInstances ),
1153 ( "AllowUndecidableInstances", Opt_AllowUndecidableInstances ),
1154 ( "AllowIncoherentInstances", Opt_AllowIncoherentInstances )
1157 impliedFlags :: [(DynFlag, [DynFlag])]
1159 ( Opt_GADTs, [Opt_RelaxedPolyRec] ) -- We want type-sig variables to be completely rigid for GADTs
1162 glasgowExtsFlags = [ Opt_GlasgowExts
1165 , Opt_ImplicitParams
1166 , Opt_ScopedTypeVariables
1167 , Opt_TypeSynonymInstances
1168 , Opt_FlexibleInstances
1169 , Opt_MultiParamTypeClasses
1170 , Opt_FunctionalDependencies
1176 , Opt_ParallelListComp
1177 , Opt_EmptyDataDecls
1178 , Opt_KindSignatures
1179 , Opt_GeneralizedNewtypeDeriving
1180 , Opt_TypeFamilies ]
1183 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1185 isFlag flags f = is_flag flags (normaliseFlag f)
1188 | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1191 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1192 -- nf is normalised alreadly
1195 getFlag, getNoFlag :: [(String,a)] -> String -> a
1197 getFlag flags f = get_flag flags (normaliseFlag f)
1199 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1200 -- The flag should be a no-flag already
1202 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1204 [] -> panic ("get_flag " ++ nf)
1207 noFlag_maybe :: String -> Maybe String
1208 -- The input is normalised already
1209 noFlag_maybe ('n' : 'o' : f) = Just f
1210 noFlag_maybe other = Nothing
1212 normaliseFlag :: String -> String
1213 -- Normalise a option flag by
1214 -- * map to lower case
1215 -- * removing hyphens
1216 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1217 normaliseFlag [] = []
1218 normaliseFlag ('-':s) = normaliseFlag s
1219 normaliseFlag (c:s) = toLower c : normaliseFlag s
1221 -- -----------------------------------------------------------------------------
1222 -- Parsing the dynamic flags.
1224 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1225 parseDynamicFlags dflags args = do
1226 let ((leftover,errs),dflags')
1227 = runCmdLine (processArgs dynamic_flags args) dflags
1228 when (not (null errs)) $ do
1229 throwDyn (UsageError (unlines errs))
1230 return (dflags', leftover)
1233 type DynP = CmdLineP DynFlags
1235 upd :: (DynFlags -> DynFlags) -> DynP ()
1237 dfs <- getCmdLineState
1238 putCmdLineState $! (f dfs)
1240 --------------------------
1241 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1242 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1244 deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1245 -- When you set f, set the ones it implies
1246 -- When you un-set f, however, we don't un-set the things it implies
1247 -- (except for -fno-glasgow-exts, which is treated specially)
1249 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1251 --------------------------
1252 setDumpFlag :: DynFlag -> OptKind DynP
1253 setDumpFlag dump_flag
1254 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1255 -- Whenver we -ddump, switch off the recompilation checker,
1256 -- else you don't see the dump!
1258 setVerbosity :: Maybe Int -> DynP ()
1259 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1261 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1263 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1266 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1268 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1270 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1273 | Nothing <- unpackPackageId pid
1274 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1276 = \s -> s{ thisPackage = pid }
1278 pid = stringToPackageId p
1280 -- If we're linking a binary, then only targets that produce object
1281 -- code are allowed (requests for other target types are ignored).
1282 setTarget l = upd set
1285 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
1288 -- Changes the target only if we're compiling object code. This is
1289 -- used by -fasm and -fvia-C, which switch from one to the other, but
1290 -- not from bytecode to object-code. The idea is that -fasm/-fvia-C
1291 -- can be safely used in an OPTIONS_GHC pragma.
1292 setObjTarget l = upd set
1295 | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1298 setOptLevel :: Int -> DynFlags -> DynFlags
1299 setOptLevel n dflags
1300 | hscTarget dflags == HscInterpreted && n > 0
1302 -- not in IO any more, oh well:
1303 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1305 = updOptLevel n dflags
1308 setMainIs :: String -> DynP ()
1310 | not (null main_fn) -- The arg looked like "Foo.baz"
1311 = upd $ \d -> d{ mainFunIs = Just main_fn,
1312 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1314 | isUpper (head main_mod) -- The arg looked like "Foo"
1315 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1317 | otherwise -- The arg looked like "baz"
1318 = upd $ \d -> d{ mainFunIs = Just main_mod }
1320 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1322 -----------------------------------------------------------------------------
1323 -- Paths & Libraries
1325 -- -i on its own deletes the import paths
1326 addImportPath "" = upd (\s -> s{importPaths = []})
1327 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1331 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1334 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1336 addFrameworkPath p =
1337 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1339 split_marker = ':' -- not configurable (ToDo)
1341 splitPathList :: String -> [String]
1342 splitPathList s = filter notNull (splitUp s)
1343 -- empty paths are ignored: there might be a trailing
1344 -- ':' in the initial list, for example. Empty paths can
1345 -- cause confusion when they are translated into -I options
1346 -- for passing to gcc.
1348 #ifndef mingw32_TARGET_OS
1349 splitUp xs = split split_marker xs
1351 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1353 -- That is, if "foo:bar:baz" is used, this interpreted as
1354 -- consisting of three entries, 'foo', 'bar', 'baz'.
1355 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1356 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1358 -- Notice that no attempt is made to fully replace the 'standard'
1359 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1360 -- that this will cause too much breakage for users & ':' will
1361 -- work fine even with DOS paths, if you're not insisting on being silly.
1364 splitUp (x:':':div:xs) | div `elem` dir_markers
1365 = ((x:':':div:p): splitUp rs)
1367 (p,rs) = findNextPath xs
1368 -- we used to check for existence of the path here, but that
1369 -- required the IO monad to be threaded through the command-line
1370 -- parser which is quite inconvenient. The
1371 splitUp xs = cons p (splitUp rs)
1373 (p,rs) = findNextPath xs
1378 -- will be called either when we've consumed nought or the
1379 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1380 -- finding the next split marker.
1382 case break (`elem` split_markers) xs of
1383 (p, d:ds) -> (p, ds)
1386 split_markers :: [Char]
1387 split_markers = [':', ';']
1389 dir_markers :: [Char]
1390 dir_markers = ['/', '\\']
1393 -- -----------------------------------------------------------------------------
1394 -- tmpDir, where we store temporary files.
1396 setTmpDir :: FilePath -> DynFlags -> DynFlags
1397 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1399 #if !defined(mingw32_HOST_OS)
1400 canonicalise p = normalisePath p
1402 -- Canonicalisation of temp path under win32 is a bit more
1403 -- involved: (a) strip trailing slash,
1404 -- (b) normalise slashes
1405 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1407 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1409 -- if we're operating under cygwin, and TMP/TEMP is of
1410 -- the form "/cygdrive/drive/path", translate this to
1411 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1412 -- understand /cygdrive paths.)
1414 | "/cygdrive/" `isPrefixOf` path =
1415 case drop (length "/cygdrive/") path of
1416 drive:xs@('/':_) -> drive:':':xs
1420 -- strip the trailing backslash (awful, but we only do this once).
1421 removeTrailingSlash path =
1428 -----------------------------------------------------------------------------
1431 setOptHpcDir :: String -> DynP ()
1432 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1434 -----------------------------------------------------------------------------
1435 -- Via-C compilation stuff
1437 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1438 [String]) -- for registerised HC compilations
1439 machdepCCOpts dflags
1440 #if alpha_TARGET_ARCH
1442 #ifdef HAVE_THREADED_RTS_SUPPORT
1446 -- For now, to suppress the gcc warning "call-clobbered
1447 -- register used for global register variable", we simply
1448 -- disable all warnings altogether using the -w flag. Oh well.
1450 #elif hppa_TARGET_ARCH
1451 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1452 -- (very nice, but too bad the HP /usr/include files don't agree.)
1453 = ( ["-D_HPUX_SOURCE"], [] )
1455 #elif m68k_TARGET_ARCH
1456 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1457 -- popping of args to routines to be explicit; if we let things
1458 -- be deferred 'til after an STGJUMP, imminent death is certain!
1460 -- -fomit-frame-pointer : *don't*
1461 -- It's better to have a6 completely tied up being a frame pointer
1462 -- rather than let GCC pick random things to do with it.
1463 -- (If we want to steal a6, then we would try to do things
1464 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1465 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1467 #elif i386_TARGET_ARCH
1468 -- -fno-defer-pop : basically the same game as for m68k
1470 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1471 -- the fp (%ebp) for our register maps.
1472 = let n_regs = stolen_x86_regs dflags
1475 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1476 -- , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else ""
1479 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1480 -- Some gccs are configured with
1481 -- -momit-leaf-frame-pointer on by default, and it
1482 -- apparently takes precedence over
1483 -- -fomit-frame-pointer, so we disable it first here.
1484 "-mno-omit-leaf-frame-pointer",
1486 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1487 "-fno-unit-at-a-time",
1488 -- unit-at-a-time doesn't do us any good, and screws
1489 -- up -split-objs by moving the split markers around.
1490 -- It's only turned on with -O2, but put it here just
1491 -- in case someone uses -optc-O2.
1493 "-fomit-frame-pointer",
1494 -- we want -fno-builtin, because when gcc inlines
1495 -- built-in functions like memcpy() it tends to
1496 -- run out of registers, requiring -monly-n-regs
1498 "-DSTOLEN_X86_REGS="++show n_regs ]
1501 #elif ia64_TARGET_ARCH
1502 = ( [], ["-fomit-frame-pointer", "-G0"] )
1504 #elif x86_64_TARGET_ARCH
1505 = ( [], ["-fomit-frame-pointer",
1506 "-fno-asynchronous-unwind-tables",
1507 -- the unwind tables are unnecessary for HC code,
1508 -- and get in the way of -split-objs. Another option
1509 -- would be to throw them away in the mangler, but this
1511 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1512 "-fno-unit-at-a-time",
1513 -- unit-at-a-time doesn't do us any good, and screws
1514 -- up -split-objs by moving the split markers around.
1515 -- It's only turned on with -O2, but put it here just
1516 -- in case someone uses -optc-O2.
1519 -- calling builtins like strlen() using the FFI can
1520 -- cause gcc to run out of regs, so use the external
1524 #elif sparc_TARGET_ARCH
1526 -- For now, to suppress the gcc warning "call-clobbered
1527 -- register used for global register variable", we simply
1528 -- disable all warnings altogether using the -w flag. Oh well.
1530 #elif powerpc_apple_darwin_TARGET
1532 -- Disable Apple's precompiling preprocessor. It's a great thing
1533 -- for "normal" programs, but it doesn't support register variable
1535 = ( [], ["-no-cpp-precomp"] )
1540 picCCOpts :: DynFlags -> [String]
1542 #if darwin_TARGET_OS
1543 -- Apple prefers to do things the other way round.
1544 -- PIC is on by default.
1545 -- -mdynamic-no-pic:
1546 -- Turn off PIC code generation.
1548 -- Don't generate "common" symbols - these are unwanted
1549 -- in dynamic libraries.
1554 = ["-mdynamic-no-pic"]
1555 #elif mingw32_TARGET_OS
1556 -- no -fPIC for Windows
1565 -- -----------------------------------------------------------------------------
1570 #if defined(i386_TARGET_ARCH) \
1571 || defined(x86_64_TARGET_ARCH) \
1572 || defined(alpha_TARGET_ARCH) \
1573 || defined(hppa_TARGET_ARCH) \
1574 || defined(m68k_TARGET_ARCH) \
1575 || defined(mips_TARGET_ARCH) \
1576 || defined(powerpc_TARGET_ARCH) \
1577 || defined(rs6000_TARGET_ARCH) \
1578 || defined(sparc_TARGET_ARCH)