Force recompilation with -ddump-minimal-imports
[ghc-hetmet.git] / compiler / main / DynFlags.hs
1 {-# OPTIONS -fno-warn-missing-fields #-}
2 -----------------------------------------------------------------------------
3 --
4 -- Dynamic flags
5 --
6 -- Most flags are dynamic flags, which means they can change from
7 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
8 -- multi-session GHC each session can be using different dynamic
9 -- flags.  Dynamic flags can also be set at the prompt in GHCi.
10 --
11 -- (c) The University of Glasgow 2005
12 --
13 -----------------------------------------------------------------------------
14
15 module DynFlags (
16         -- Dynamic flags
17         DynFlag(..),
18         DynFlags(..),
19         HscTarget(..),
20         GhcMode(..), isOneShot,
21         GhcLink(..), isNoLink,
22         PackageFlag(..),
23         Option(..),
24
25         -- Configuration of the core-to-core and stg-to-stg phases
26         CoreToDo(..),
27         StgToDo(..),
28         SimplifierSwitch(..), 
29         SimplifierMode(..), FloatOutSwitches(..),
30         getCoreToDo, getStgToDo,
31         
32         -- Manipulating DynFlags
33         defaultDynFlags,                -- DynFlags
34         initDynFlags,                   -- DynFlags -> IO DynFlags
35
36         dopt,                           -- DynFlag -> DynFlags -> Bool
37         dopt_set, dopt_unset,           -- DynFlags -> DynFlag -> DynFlags
38         getOpts,                        -- (DynFlags -> [a]) -> IO [a]
39         getVerbFlag,
40         updOptLevel,
41         setTmpDir,
42         setPackageName,
43         
44         -- parsing DynFlags
45         parseDynamicFlags,
46         allFlags,
47
48         -- misc stuff
49         machdepCCOpts, picCCOpts
50   ) where
51
52 #include "HsVersions.h"
53
54 import Module           ( Module, mkModuleName, mkModule )
55 import PackageConfig
56 import PrelNames        ( mAIN )
57 #ifdef i386_TARGET_ARCH
58 import StaticFlags      ( opt_Static )
59 #endif
60 import StaticFlags      ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
61                           v_RTS_Build_tag )
62 import {-# SOURCE #-} Packages (PackageState)
63 import DriverPhases     ( Phase(..), phaseInputExt )
64 import Config
65 import CmdLineParser
66 import Constants        ( mAX_CONTEXT_REDUCTION_DEPTH )
67 import Panic            ( panic, GhcException(..) )
68 import UniqFM           ( UniqFM )
69 import Util             ( notNull, splitLongestPrefix, normalisePath )
70 import Maybes           ( fromJust, orElse )
71 import SrcLoc           ( SrcSpan )
72 import Outputable
73 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
74
75 import Data.IORef       ( readIORef )
76 import Control.Exception ( throwDyn )
77 import Control.Monad    ( when )
78 #ifdef mingw32_TARGET_OS
79 import Data.List        ( isPrefixOf )
80 #else
81 import Util             ( split )
82 #endif
83
84 import Data.Char        ( isUpper )
85 import System.IO        ( hPutStrLn, stderr )
86
87 #ifdef GHCI
88 import Breakpoints      ( BkptHandler )
89 import Module           ( ModuleName )
90 #endif
91 -- -----------------------------------------------------------------------------
92 -- DynFlags
93
94 data DynFlag
95
96    -- debugging flags
97    = Opt_D_dump_cmm
98    | Opt_D_dump_asm
99    | Opt_D_dump_cpranal
100    | Opt_D_dump_deriv
101    | Opt_D_dump_ds
102    | Opt_D_dump_flatC
103    | Opt_D_dump_foreign
104    | Opt_D_dump_inlinings
105    | Opt_D_dump_rule_firings
106    | Opt_D_dump_occur_anal
107    | Opt_D_dump_parsed
108    | Opt_D_dump_rn
109    | Opt_D_dump_simpl
110    | Opt_D_dump_simpl_iterations
111    | Opt_D_dump_spec
112    | Opt_D_dump_prep
113    | Opt_D_dump_stg
114    | Opt_D_dump_stranal
115    | Opt_D_dump_tc
116    | Opt_D_dump_types
117    | Opt_D_dump_rules
118    | Opt_D_dump_cse
119    | Opt_D_dump_worker_wrapper
120    | Opt_D_dump_rn_trace
121    | Opt_D_dump_rn_stats
122    | Opt_D_dump_opt_cmm
123    | Opt_D_dump_simpl_stats
124    | Opt_D_dump_tc_trace
125    | Opt_D_dump_if_trace
126    | Opt_D_dump_splices
127    | Opt_D_dump_BCOs
128    | Opt_D_dump_vect
129    | Opt_D_dump_hpc
130    | Opt_D_source_stats
131    | Opt_D_verbose_core2core
132    | Opt_D_verbose_stg2stg
133    | Opt_D_dump_hi
134    | Opt_D_dump_hi_diffs
135    | Opt_D_dump_minimal_imports
136    | Opt_D_faststring_stats
137    | Opt_DoCoreLinting
138    | Opt_DoStgLinting
139    | Opt_DoCmmLinting
140
141    | Opt_WarnIsError            -- -Werror; makes warnings fatal
142    | Opt_WarnDuplicateExports
143    | Opt_WarnHiShadows
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_WarnUnusedBinds
154    | Opt_WarnUnusedImports
155    | Opt_WarnUnusedMatches
156    | Opt_WarnDeprecations
157    | Opt_WarnDodgyImports
158    | Opt_WarnOrphans
159    | Opt_WarnTabs
160
161    -- language opts
162    | Opt_AllowOverlappingInstances
163    | Opt_AllowUndecidableInstances
164    | Opt_AllowIncoherentInstances
165    | Opt_MonomorphismRestriction
166    | Opt_MonoPatBinds
167    | Opt_ExtendedDefaultRules           -- Use GHC's extended rules for defaulting
168    | Opt_GlasgowExts
169    | Opt_FFI
170    | Opt_PArr                           -- Syntactic support for parallel arrays
171    | Opt_Arrows                         -- Arrow-notation syntax
172    | Opt_TH
173    | Opt_ImplicitParams
174    | Opt_Generics
175    | Opt_ImplicitPrelude 
176    | Opt_ScopedTypeVariables
177    | Opt_BangPatterns
178    | Opt_IndexedTypes
179    | Opt_OverloadedStrings
180
181    -- optimisation opts
182    | Opt_Strictness
183    | Opt_FullLaziness
184    | Opt_CSE
185    | Opt_IgnoreInterfacePragmas
186    | Opt_OmitInterfacePragmas
187    | Opt_DoLambdaEtaExpansion
188    | Opt_IgnoreAsserts
189    | Opt_IgnoreBreakpoints
190    | Opt_DoEtaReduction
191    | Opt_CaseMerge
192    | Opt_UnboxStrictFields
193    | Opt_DictsCheap
194
195    -- misc opts
196    | Opt_Cpp
197    | Opt_Pp
198    | Opt_ForceRecomp
199    | Opt_DryRun
200    | Opt_DoAsmMangling
201    | Opt_ExcessPrecision
202    | Opt_ReadUserPackageConf
203    | Opt_NoHsMain
204    | Opt_SplitObjs
205    | Opt_StgStats
206    | Opt_HideAllPackages
207 #if defined(GHCI) && defined(DEBUGGER)
208    | Opt_Debugging
209 #endif
210    | Opt_PrintBindResult
211    | Opt_Haddock
212    | Opt_Hpc_No_Auto
213
214    -- keeping stuff
215    | Opt_KeepHiDiffs
216    | Opt_KeepHcFiles
217    | Opt_KeepSFiles
218    | Opt_KeepRawSFiles
219    | Opt_KeepTmpFiles
220
221    deriving (Eq)
222  
223 data DynFlags = DynFlags {
224   ghcMode               :: GhcMode,
225   ghcLink               :: GhcLink,
226   coreToDo              :: Maybe [CoreToDo], -- reserved for -Ofile
227   stgToDo               :: Maybe [StgToDo],  -- similarly
228   hscTarget             :: HscTarget,
229   hscOutName            :: String,      -- name of the output file
230   extCoreName           :: String,      -- name of the .core output file
231   verbosity             :: Int,         -- verbosity level
232   optLevel              :: Int,         -- optimisation level
233   maxSimplIterations    :: Int,         -- max simplifier iterations
234   ruleCheck             :: Maybe String,
235   libCaseThreshold      :: Int,         -- Threshold for liberate-case
236
237   stolen_x86_regs       :: Int,         
238   cmdlineHcIncludes     :: [String],    -- -#includes
239   importPaths           :: [FilePath],
240   mainModIs             :: Module,
241   mainFunIs             :: Maybe String,
242   ctxtStkDepth          :: Int,         -- Typechecker context stack depth
243
244   thisPackage           :: PackageId,
245
246   -- ways
247   wayNames              :: [WayName],   -- way flags from the cmd line
248   buildTag              :: String,      -- the global "way" (eg. "p" for prof)
249   rtsBuildTag           :: String,      -- the RTS "way"
250   
251   -- paths etc.
252   objectDir             :: Maybe String,
253   hiDir                 :: Maybe String,
254   stubDir               :: Maybe String,
255
256   objectSuf             :: String,
257   hcSuf                 :: String,
258   hiSuf                 :: String,
259
260   outputFile            :: Maybe String,
261   outputHi              :: Maybe String,
262
263   includePaths          :: [String],
264   libraryPaths          :: [String],
265   frameworkPaths        :: [String],    -- used on darwin only
266   cmdlineFrameworks     :: [String],    -- ditto
267   tmpDir                :: String,      -- no trailing '/'
268   
269   ghcUsagePath          :: FilePath,    -- Filled in by SysTools
270   ghciUsagePath         :: FilePath,    -- ditto
271
272   hpcDir                :: String,      -- ^ path to store the .mix files
273
274   -- options for particular phases
275   opt_L                 :: [String],
276   opt_P                 :: [String],
277   opt_F                 :: [String],
278   opt_c                 :: [String],
279   opt_m                 :: [String],
280   opt_a                 :: [String],
281   opt_l                 :: [String],
282   opt_dll               :: [String],
283   opt_dep               :: [String],
284
285   -- commands for particular phases
286   pgm_L                 :: String,
287   pgm_P                 :: (String,[Option]),
288   pgm_F                 :: String,
289   pgm_c                 :: (String,[Option]),
290   pgm_m                 :: (String,[Option]),
291   pgm_s                 :: (String,[Option]),
292   pgm_a                 :: (String,[Option]),
293   pgm_l                 :: (String,[Option]),
294   pgm_dll               :: (String,[Option]),
295   pgm_T                 :: String,
296   pgm_sysman            :: String,
297
298   --  Package flags
299   extraPkgConfs         :: [FilePath],
300   topDir                :: FilePath,    -- filled in by SysTools
301   systemPackageConfig   :: FilePath,    -- ditto
302         -- The -package-conf flags given on the command line, in the order
303         -- they appeared.
304
305   packageFlags          :: [PackageFlag],
306         -- The -package and -hide-package flags from the command-line
307
308   -- Package state
309   -- NB. do not modify this field, it is calculated by 
310   -- Packages.initPackages and Packages.updatePackages.
311   pkgDatabase           :: Maybe (UniqFM InstalledPackageInfo),
312   pkgState              :: PackageState,
313
314   -- hsc dynamic flags
315   flags                 :: [DynFlag],
316   
317   -- message output
318   log_action            :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
319
320 #ifdef GHCI
321   -- breakpoint handling
322  ,bkptHandler           :: Maybe (BkptHandler Module)
323 #endif
324  }
325
326 data HscTarget
327   = HscC
328   | HscAsm
329   | HscJava
330   | HscInterpreted
331   | HscNothing
332   deriving (Eq, Show)
333
334 data GhcMode
335   = BatchCompile        -- | @ghc --make Main@
336   | Interactive         -- | @ghc --interactive@
337   | OneShot             -- | @ghc -c Foo.hs@
338   | JustTypecheck       -- | Development environemnts, refactorer, etc.
339   | MkDepend
340   deriving Eq
341
342 isOneShot :: GhcMode -> Bool
343 isOneShot OneShot = True
344 isOneShot _other  = False
345
346 data GhcLink    -- What to do in the link step, if there is one
347   =             -- Only relevant for modes
348                 --      DoMake and StopBefore StopLn
349     NoLink              -- Don't link at all
350   | StaticLink          -- Ordinary linker [the default]
351   | MkDLL               -- Make a DLL
352
353 isNoLink :: GhcLink -> Bool
354 isNoLink NoLink = True
355 isNoLink other  = False
356
357 data PackageFlag
358   = ExposePackage  String
359   | HidePackage    String
360   | IgnorePackage  String
361   deriving Eq
362
363 defaultHscTarget
364   | cGhcWithNativeCodeGen == "YES"      =  HscAsm
365   | otherwise                           =  HscC
366
367 initDynFlags dflags = do
368  -- someday these will be dynamic flags
369  ways <- readIORef v_Ways
370  build_tag <- readIORef v_Build_tag
371  rts_build_tag <- readIORef v_RTS_Build_tag
372  return dflags{
373         wayNames        = ways,
374         buildTag        = build_tag,
375         rtsBuildTag     = rts_build_tag
376         }
377
378 defaultDynFlags =
379      DynFlags {
380         ghcMode                 = OneShot,
381         ghcLink                 = StaticLink,
382         coreToDo                = Nothing,
383         stgToDo                 = Nothing, 
384         hscTarget               = defaultHscTarget, 
385         hscOutName              = "", 
386         extCoreName             = "",
387         verbosity               = 0, 
388         optLevel                = 0,
389         maxSimplIterations      = 4,
390         ruleCheck               = Nothing,
391         libCaseThreshold        = 20,
392         stolen_x86_regs         = 4,
393         cmdlineHcIncludes       = [],
394         importPaths             = ["."],
395         mainModIs               = mAIN,
396         mainFunIs               = Nothing,
397         ctxtStkDepth            = mAX_CONTEXT_REDUCTION_DEPTH,
398
399         thisPackage             = mainPackageId,
400
401         objectDir               = Nothing,
402         hiDir                   = Nothing,
403         stubDir                 = Nothing,
404
405         objectSuf               = phaseInputExt StopLn,
406         hcSuf                   = phaseInputExt HCc,
407         hiSuf                   = "hi",
408
409         outputFile              = Nothing,
410         outputHi                = Nothing,
411         includePaths            = [],
412         libraryPaths            = [],
413         frameworkPaths          = [],
414         cmdlineFrameworks       = [],
415         tmpDir                  = cDEFAULT_TMPDIR,
416         
417         hpcDir                  = ".hpc",
418
419         opt_L                   = [],
420         opt_P                   = [],
421         opt_F                   = [],
422         opt_c                   = [],
423         opt_a                   = [],
424         opt_m                   = [],
425         opt_l                   = [],
426         opt_dll                 = [],
427         opt_dep                 = [],
428         
429         extraPkgConfs           = [],
430         packageFlags            = [],
431         pkgDatabase             = Nothing,
432         pkgState                = panic "no package state yet: call GHC.setSessionDynFlags",
433 #ifdef GHCI
434         bkptHandler             = Nothing,
435 #endif
436         flags = [ 
437             Opt_ReadUserPackageConf,
438     
439             Opt_MonoPatBinds,   -- Experimentally, I'm making this non-standard
440                                 -- behaviour the default, to see if anyone notices
441                                 -- SLPJ July 06
442
443             Opt_ImplicitPrelude,
444             Opt_MonomorphismRestriction,
445             Opt_Strictness,
446                         -- strictness is on by default, but this only
447                         -- applies to -O.
448             Opt_CSE,            -- similarly for CSE.
449             Opt_FullLaziness,   -- ...and for full laziness
450     
451             Opt_DoLambdaEtaExpansion,
452                         -- This one is important for a tiresome reason:
453                         -- we want to make sure that the bindings for data 
454                         -- constructors are eta-expanded.  This is probably
455                         -- a good thing anyway, but it seems fragile.
456     
457             Opt_DoAsmMangling,
458     
459             -- and the default no-optimisation options:
460             Opt_IgnoreInterfacePragmas,
461             Opt_OmitInterfacePragmas,
462     
463             -- on by default:
464             Opt_PrintBindResult
465                ] ++ standardWarnings,
466                
467         log_action = \severity srcSpan style msg -> 
468                         case severity of
469                           SevInfo  -> hPutStrLn stderr (show (msg style))
470                           SevFatal -> hPutStrLn stderr (show (msg style))
471                           _        -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
472       }
473
474 {- 
475     Verbosity levels:
476         
477     0   |   print errors & warnings only
478     1   |   minimal verbosity: print "compiling M ... done." for each module.
479     2   |   equivalent to -dshow-passes
480     3   |   equivalent to existing "ghc -v"
481     4   |   "ghc -v -ddump-most"
482     5   |   "ghc -v -ddump-all"
483 -}
484
485 dopt :: DynFlag -> DynFlags -> Bool
486 dopt f dflags  = f `elem` (flags dflags)
487
488 dopt_set :: DynFlags -> DynFlag -> DynFlags
489 dopt_set dfs f = dfs{ flags = f : flags dfs }
490
491 dopt_unset :: DynFlags -> DynFlag -> DynFlags
492 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
493
494 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
495 getOpts dflags opts = reverse (opts dflags)
496         -- We add to the options from the front, so we need to reverse the list
497
498 getVerbFlag :: DynFlags -> String
499 getVerbFlag dflags 
500   | verbosity dflags >= 3  = "-v" 
501   | otherwise =  ""
502
503 setObjectDir  f d = d{ objectDir  = f}
504 setHiDir      f d = d{ hiDir      = f}
505 setStubDir    f d = d{ stubDir    = f}
506
507 setObjectSuf  f d = d{ objectSuf  = f}
508 setHiSuf      f d = d{ hiSuf      = f}
509 setHcSuf      f d = d{ hcSuf      = f}
510
511 setOutputFile f d = d{ outputFile = f}
512 setOutputHi   f d = d{ outputHi   = f}
513
514 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
515 -- Config.hs should really use Option.
516 setPgmP   f d = let (pgm:args) = words f in d{ pgm_P   = (pgm, map Option args)}
517
518 setPgmL   f d = d{ pgm_L   = f}
519 setPgmF   f d = d{ pgm_F   = f}
520 setPgmc   f d = d{ pgm_c   = (f,[])}
521 setPgmm   f d = d{ pgm_m   = (f,[])}
522 setPgms   f d = d{ pgm_s   = (f,[])}
523 setPgma   f d = d{ pgm_a   = (f,[])}
524 setPgml   f d = d{ pgm_l   = (f,[])}
525 setPgmdll f d = d{ pgm_dll = (f,[])}
526
527 addOptL   f d = d{ opt_L   = f : opt_L d}
528 addOptP   f d = d{ opt_P   = f : opt_P d}
529 addOptF   f d = d{ opt_F   = f : opt_F d}
530 addOptc   f d = d{ opt_c   = f : opt_c d}
531 addOptm   f d = d{ opt_m   = f : opt_m d}
532 addOpta   f d = d{ opt_a   = f : opt_a d}
533 addOptl   f d = d{ opt_l   = f : opt_l d}
534 addOptdll f d = d{ opt_dll = f : opt_dll d}
535 addOptdep f d = d{ opt_dep = f : opt_dep d}
536
537 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
538
539 -- -----------------------------------------------------------------------------
540 -- Command-line options
541
542 -- When invoking external tools as part of the compilation pipeline, we
543 -- pass these a sequence of options on the command-line. Rather than
544 -- just using a list of Strings, we use a type that allows us to distinguish
545 -- between filepaths and 'other stuff'. [The reason being, of course, that
546 -- this type gives us a handle on transforming filenames, and filenames only,
547 -- to whatever format they're expected to be on a particular platform.]
548
549 data Option
550  = FileOption -- an entry that _contains_ filename(s) / filepaths.
551               String  -- a non-filepath prefix that shouldn't be 
552                       -- transformed (e.g., "/out=")
553               String  -- the filepath/filename portion
554  | Option     String
555  
556 -----------------------------------------------------------------------------
557 -- Setting the optimisation level
558
559 updOptLevel :: Int -> DynFlags -> DynFlags
560 -- Set dynflags appropriate to the optimisation level
561 updOptLevel n dfs
562   = dfs2{ optLevel = n }
563   where
564    dfs1 = foldr (flip dopt_unset) dfs  remove_dopts
565    dfs2 = foldr (flip dopt_set)   dfs1 extra_dopts
566
567    extra_dopts
568         | n == 0    = opt_0_dopts
569         | otherwise = opt_1_dopts
570
571    remove_dopts
572         | n == 0    = opt_1_dopts
573         | otherwise = opt_0_dopts
574         
575 opt_0_dopts =  [ 
576         Opt_IgnoreInterfacePragmas,
577         Opt_OmitInterfacePragmas
578     ]
579
580 opt_1_dopts = [
581         Opt_IgnoreAsserts,
582         Opt_DoEtaReduction,
583         Opt_CaseMerge
584      ]
585
586 -- -----------------------------------------------------------------------------
587 -- Standard sets of warning options
588
589 standardWarnings
590     = [ Opt_WarnDeprecations,
591         Opt_WarnOverlappingPatterns,
592         Opt_WarnMissingFields,
593         Opt_WarnMissingMethods,
594         Opt_WarnDuplicateExports
595       ]
596
597 minusWOpts
598     = standardWarnings ++ 
599       [ Opt_WarnUnusedBinds,
600         Opt_WarnUnusedMatches,
601         Opt_WarnUnusedImports,
602         Opt_WarnIncompletePatterns,
603         Opt_WarnDodgyImports
604       ]
605
606 minusWallOpts
607     = minusWOpts ++
608       [ Opt_WarnTypeDefaults,
609         Opt_WarnNameShadowing,
610         Opt_WarnMissingSigs,
611         Opt_WarnHiShadows,
612         Opt_WarnOrphans
613       ]
614
615 -- -----------------------------------------------------------------------------
616 -- CoreToDo:  abstraction of core-to-core passes to run.
617
618 data CoreToDo           -- These are diff core-to-core passes,
619                         -- which may be invoked in any order,
620                         -- as many times as you like.
621
622   = CoreDoSimplify      -- The core-to-core simplifier.
623         SimplifierMode
624         [SimplifierSwitch]
625                         -- Each run of the simplifier can take a different
626                         -- set of simplifier-specific flags.
627   | CoreDoFloatInwards
628   | CoreDoFloatOutwards FloatOutSwitches
629   | CoreLiberateCase
630   | CoreDoPrintCore
631   | CoreDoStaticArgs
632   | CoreDoStrictness
633   | CoreDoWorkerWrapper
634   | CoreDoSpecialising
635   | CoreDoSpecConstr
636   | CoreDoOldStrictness
637   | CoreDoGlomBinds
638   | CoreCSE
639   | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules 
640                                                 -- matching this string
641
642   | CoreDoNothing        -- useful when building up lists of these things
643
644 data SimplifierMode             -- See comments in SimplMonad
645   = SimplGently
646   | SimplPhase Int
647
648 data SimplifierSwitch
649   = MaxSimplifierIterations Int
650   | NoCaseOfCase
651
652 data FloatOutSwitches
653   = FloatOutSw  Bool    -- True <=> float lambdas to top level
654                 Bool    -- True <=> float constants to top level,
655                         --          even if they do not escape a lambda
656
657
658 -- The core-to-core pass ordering is derived from the DynFlags:
659
660 getCoreToDo :: DynFlags -> [CoreToDo]
661 getCoreToDo dflags
662   | Just todo <- coreToDo dflags = todo -- set explicitly by user
663   | otherwise = core_todo
664   where
665     opt_level     = optLevel dflags
666     max_iter      = maxSimplIterations dflags
667     strictness    = dopt Opt_Strictness dflags
668     full_laziness = dopt Opt_FullLaziness dflags
669     cse           = dopt Opt_CSE dflags
670     rule_check    = ruleCheck dflags
671
672     core_todo = 
673      if opt_level == 0 then
674       [
675         CoreDoSimplify (SimplPhase 0) [
676             MaxSimplifierIterations max_iter
677         ]
678       ]
679      else {- opt_level >= 1 -} [ 
680
681         -- initial simplify: mk specialiser happy: minimum effort please
682         CoreDoSimplify SimplGently [
683                         --      Simplify "gently"
684                         -- Don't inline anything till full laziness has bitten
685                         -- In particular, inlining wrappers inhibits floating
686                         -- e.g. ...(case f x of ...)...
687                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
688                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
689                         -- and now the redex (f x) isn't floatable any more
690                         -- Similarly, don't apply any rules until after full 
691                         -- laziness.  Notably, list fusion can prevent floating.
692
693             NoCaseOfCase,       -- Don't do case-of-case transformations.
694                                 -- This makes full laziness work better
695             MaxSimplifierIterations max_iter
696         ],
697
698         -- Specialisation is best done before full laziness
699         -- so that overloaded functions have all their dictionary lambdas manifest
700         CoreDoSpecialising,
701
702         if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
703                          else CoreDoNothing,
704
705         CoreDoFloatInwards,
706
707         CoreDoSimplify (SimplPhase 2) [
708                 -- Want to run with inline phase 2 after the specialiser to give
709                 -- maximum chance for fusion to work before we inline build/augment
710                 -- in phase 1.  This made a difference in 'ansi' where an 
711                 -- overloaded function wasn't inlined till too late.
712            MaxSimplifierIterations max_iter
713         ],
714         case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
715
716         CoreDoSimplify (SimplPhase 1) [
717                 -- Need inline-phase2 here so that build/augment get 
718                 -- inlined.  I found that spectral/hartel/genfft lost some useful
719                 -- strictness in the function sumcode' if augment is not inlined
720                 -- before strictness analysis runs
721            MaxSimplifierIterations max_iter
722         ],
723         case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
724
725         CoreDoSimplify (SimplPhase 0) [
726                 -- Phase 0: allow all Ids to be inlined now
727                 -- This gets foldr inlined before strictness analysis
728
729            MaxSimplifierIterations 3
730                 -- At least 3 iterations because otherwise we land up with
731                 -- huge dead expressions because of an infelicity in the 
732                 -- simpifier.   
733                 --      let k = BIG in foldr k z xs
734                 -- ==>  let k = BIG in letrec go = \xs -> ...(k x).... in go xs
735                 -- ==>  let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
736                 -- Don't stop now!
737
738         ],
739         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
740
741 #ifdef OLD_STRICTNESS
742         CoreDoOldStrictness
743 #endif
744         if strictness then CoreDoStrictness else CoreDoNothing,
745         CoreDoWorkerWrapper,
746         CoreDoGlomBinds,
747
748         CoreDoSimplify (SimplPhase 0) [
749            MaxSimplifierIterations max_iter
750         ],
751
752         if full_laziness then
753           CoreDoFloatOutwards (FloatOutSw False   -- Not lambdas
754                                           True)   -- Float constants
755         else CoreDoNothing,
756                 -- nofib/spectral/hartel/wang doubles in speed if you
757                 -- do full laziness late in the day.  It only happens
758                 -- after fusion and other stuff, so the early pass doesn't
759                 -- catch it.  For the record, the redex is 
760                 --        f_el22 (f_el21 r_midblock)
761
762
763         -- We want CSE to follow the final full-laziness pass, because it may
764         -- succeed in commoning up things floated out by full laziness.
765         -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
766
767         if cse then CoreCSE else CoreDoNothing,
768
769         CoreDoFloatInwards,
770
771 -- Case-liberation for -O2.  This should be after
772 -- strictness analysis and the simplification which follows it.
773
774         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
775      ]
776
777         ++ 
778
779      (if opt_level >= 2 then
780            [  CoreLiberateCase,
781               CoreDoSimplify (SimplPhase 0) [
782                   MaxSimplifierIterations max_iter
783               ],        -- Run the simplifier after LiberateCase to vastly 
784                         -- reduce the possiblility of shadowing
785                         -- Reason: see Note [Shadowing] in SpecConstr.lhs
786              CoreDoSpecConstr
787            ]
788       else
789            [])
790
791         ++
792
793         -- Final clean-up simplification:
794      [  CoreDoSimplify (SimplPhase 0) [
795           MaxSimplifierIterations max_iter
796         ]
797      ]
798
799 -- -----------------------------------------------------------------------------
800 -- StgToDo:  abstraction of stg-to-stg passes to run.
801
802 data StgToDo
803   = StgDoMassageForProfiling  -- should be (next to) last
804   -- There's also setStgVarInfo, but its absolute "lastness"
805   -- is so critical that it is hardwired in (no flag).
806   | D_stg_stats
807
808 getStgToDo :: DynFlags -> [StgToDo]
809 getStgToDo dflags
810   | Just todo <- stgToDo dflags = todo -- set explicitly by user
811   | otherwise = todo2
812   where
813         stg_stats = dopt Opt_StgStats dflags
814
815         todo1 = if stg_stats then [D_stg_stats] else []
816
817         todo2 | WayProf `elem` wayNames dflags
818               = StgDoMassageForProfiling : todo1
819               | otherwise
820               = todo1
821
822 -- -----------------------------------------------------------------------------
823 -- DynFlags parser
824
825 allFlags :: [String]
826 allFlags = map ('-':) $
827            [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
828            map ("fno-"++) flags ++
829            map ("f"++) flags
830     where ok (PrefixPred _ _) = False
831           ok _ = True
832           flags = map fst fFlags
833
834 dynamic_flags :: [(String, OptKind DynP)]
835 dynamic_flags = [
836      ( "n"              , NoArg  (setDynFlag Opt_DryRun) )
837   ,  ( "cpp"            , NoArg  (setDynFlag Opt_Cpp))
838   ,  ( "F"              , NoArg  (setDynFlag Opt_Pp))
839   ,  ( "#include"       , HasArg (addCmdlineHCInclude) )
840   ,  ( "v"              , OptIntSuffix setVerbosity )
841
842         ------- Specific phases  --------------------------------------------
843   ,  ( "pgmL"           , HasArg (upd . setPgmL) )  
844   ,  ( "pgmP"           , HasArg (upd . setPgmP) )  
845   ,  ( "pgmF"           , HasArg (upd . setPgmF) )  
846   ,  ( "pgmc"           , HasArg (upd . setPgmc) )  
847   ,  ( "pgmm"           , HasArg (upd . setPgmm) )  
848   ,  ( "pgms"           , HasArg (upd . setPgms) )  
849   ,  ( "pgma"           , HasArg (upd . setPgma) )  
850   ,  ( "pgml"           , HasArg (upd . setPgml) )  
851   ,  ( "pgmdll"         , HasArg (upd . setPgmdll) )
852
853   ,  ( "optL"           , HasArg (upd . addOptL) )  
854   ,  ( "optP"           , HasArg (upd . addOptP) )  
855   ,  ( "optF"           , HasArg (upd . addOptF) )  
856   ,  ( "optc"           , HasArg (upd . addOptc) )  
857   ,  ( "optm"           , HasArg (upd . addOptm) )  
858   ,  ( "opta"           , HasArg (upd . addOpta) )  
859   ,  ( "optl"           , HasArg (upd . addOptl) )  
860   ,  ( "optdll"         , HasArg (upd . addOptdll) )  
861   ,  ( "optdep"         , HasArg (upd . addOptdep) )
862
863   ,  ( "split-objs"     , NoArg (if can_split
864                                     then setDynFlag Opt_SplitObjs
865                                     else return ()) )
866
867         -------- Linking ----------------------------------------------------
868   ,  ( "c"              , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
869   ,  ( "no-link"        , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
870   ,  ( "-mk-dll"        , NoArg (upd $ \d -> d{ ghcLink=MkDLL } ))
871
872         ------- Libraries ---------------------------------------------------
873   ,  ( "L"              , Prefix addLibraryPath )
874   ,  ( "l"              , AnySuffix (\s -> do upd (addOptl s)
875                                               upd (addOptdll s)))
876
877         ------- Frameworks --------------------------------------------------
878         -- -framework-path should really be -F ...
879   ,  ( "framework-path" , HasArg addFrameworkPath )
880   ,  ( "framework"      , HasArg (upd . addCmdlineFramework) )
881
882         ------- Output Redirection ------------------------------------------
883   ,  ( "odir"           , HasArg (upd . setObjectDir  . Just))
884   ,  ( "o"              , SepArg (upd . setOutputFile . Just))
885   ,  ( "ohi"            , HasArg (upd . setOutputHi   . Just ))
886   ,  ( "osuf"           , HasArg (upd . setObjectSuf))
887   ,  ( "hcsuf"          , HasArg (upd . setHcSuf))
888   ,  ( "hisuf"          , HasArg (upd . setHiSuf))
889   ,  ( "hidir"          , HasArg (upd . setHiDir . Just))
890   ,  ( "tmpdir"         , HasArg (upd . setTmpDir))
891   ,  ( "stubdir"        , HasArg (upd . setStubDir . Just))
892
893         ------- Keeping temporary files -------------------------------------
894   ,  ( "keep-hc-file"   , AnySuffix (\_ -> setDynFlag Opt_KeepHcFiles))
895   ,  ( "keep-s-file"    , AnySuffix (\_ -> setDynFlag Opt_KeepSFiles))
896   ,  ( "keep-raw-s-file", AnySuffix (\_ -> setDynFlag Opt_KeepRawSFiles))
897   ,  ( "keep-tmp-files" , AnySuffix (\_ -> setDynFlag Opt_KeepTmpFiles))
898
899         ------- Miscellaneous ----------------------------------------------
900   ,  ( "no-hs-main"     , NoArg (setDynFlag Opt_NoHsMain))
901   ,  ( "main-is"        , SepArg setMainIs )
902   ,  ( "haddock"        , NoArg (setDynFlag Opt_Haddock) )
903   ,  ( "hpcdir"         , SepArg setOptHpcDir )
904
905         ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
906   ,  ( "recomp"         , NoArg (unSetDynFlag Opt_ForceRecomp) )
907   ,  ( "no-recomp"      , NoArg (setDynFlag   Opt_ForceRecomp) )
908
909         ------- Packages ----------------------------------------------------
910   ,  ( "package-conf"   , HasArg extraPkgConf_ )
911   ,  ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
912   ,  ( "package-name"   , HasArg (upd . setPackageName) )
913   ,  ( "package"        , HasArg exposePackage )
914   ,  ( "hide-package"   , HasArg hidePackage )
915   ,  ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
916   ,  ( "ignore-package" , HasArg ignorePackage )
917   ,  ( "syslib"         , HasArg exposePackage )  -- for compatibility
918
919         ------ HsCpp opts ---------------------------------------------------
920   ,  ( "D",             AnySuffix (upd . addOptP) )
921   ,  ( "U",             AnySuffix (upd . addOptP) )
922
923         ------- Include/Import Paths ----------------------------------------
924   ,  ( "I"              , Prefix    addIncludePath)
925   ,  ( "i"              , OptPrefix addImportPath )
926
927         ------ Debugging ----------------------------------------------------
928   ,  ( "dstg-stats",    NoArg (setDynFlag Opt_StgStats))
929
930   ,  ( "ddump-cmm",              setDumpFlag Opt_D_dump_cmm)
931   ,  ( "ddump-asm",              setDumpFlag Opt_D_dump_asm)
932   ,  ( "ddump-cpranal",          setDumpFlag Opt_D_dump_cpranal)
933   ,  ( "ddump-deriv",            setDumpFlag Opt_D_dump_deriv)
934   ,  ( "ddump-ds",               setDumpFlag Opt_D_dump_ds)
935   ,  ( "ddump-flatC",            setDumpFlag Opt_D_dump_flatC)
936   ,  ( "ddump-foreign",          setDumpFlag Opt_D_dump_foreign)
937   ,  ( "ddump-inlinings",        setDumpFlag Opt_D_dump_inlinings)
938   ,  ( "ddump-rule-firings",     setDumpFlag Opt_D_dump_rule_firings)
939   ,  ( "ddump-occur-anal",       setDumpFlag Opt_D_dump_occur_anal)
940   ,  ( "ddump-parsed",           setDumpFlag Opt_D_dump_parsed)
941   ,  ( "ddump-rn",               setDumpFlag Opt_D_dump_rn)
942   ,  ( "ddump-simpl",            setDumpFlag Opt_D_dump_simpl)
943   ,  ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
944   ,  ( "ddump-spec",             setDumpFlag Opt_D_dump_spec)
945   ,  ( "ddump-prep",             setDumpFlag Opt_D_dump_prep)
946   ,  ( "ddump-stg",              setDumpFlag Opt_D_dump_stg)
947   ,  ( "ddump-stranal",          setDumpFlag Opt_D_dump_stranal)
948   ,  ( "ddump-tc",               setDumpFlag Opt_D_dump_tc)
949   ,  ( "ddump-types",            setDumpFlag Opt_D_dump_types)
950   ,  ( "ddump-rules",            setDumpFlag Opt_D_dump_rules)
951   ,  ( "ddump-cse",              setDumpFlag Opt_D_dump_cse)
952   ,  ( "ddump-worker-wrapper",   setDumpFlag Opt_D_dump_worker_wrapper)
953   ,  ( "ddump-rn-trace",         NoArg (setDynFlag Opt_D_dump_rn_trace))
954   ,  ( "ddump-if-trace",         NoArg (setDynFlag Opt_D_dump_if_trace))
955   ,  ( "ddump-tc-trace",         setDumpFlag Opt_D_dump_tc_trace)
956   ,  ( "ddump-splices",          setDumpFlag Opt_D_dump_splices)
957   ,  ( "ddump-rn-stats",         NoArg (setDynFlag Opt_D_dump_rn_stats))
958   ,  ( "ddump-opt-cmm",          setDumpFlag Opt_D_dump_opt_cmm)
959   ,  ( "ddump-simpl-stats",      setDumpFlag Opt_D_dump_simpl_stats)
960   ,  ( "ddump-bcos",             setDumpFlag Opt_D_dump_BCOs)
961   ,  ( "dsource-stats",          setDumpFlag Opt_D_source_stats)
962   ,  ( "dverbose-core2core",     setDumpFlag Opt_D_verbose_core2core)
963   ,  ( "dverbose-stg2stg",       setDumpFlag Opt_D_verbose_stg2stg)
964   ,  ( "ddump-hi-diffs",         NoArg (setDynFlag Opt_D_dump_hi_diffs))
965   ,  ( "ddump-hi",               setDumpFlag Opt_D_dump_hi)
966   ,  ( "ddump-minimal-imports",  setDumpFlag Opt_D_dump_minimal_imports)
967   ,  ( "ddump-vect",             setDumpFlag Opt_D_dump_vect)
968   ,  ( "ddump-hpc",              setDumpFlag Opt_D_dump_hpc)
969   
970   ,  ( "dcore-lint",             NoArg (setDynFlag Opt_DoCoreLinting))
971   ,  ( "dstg-lint",              NoArg (setDynFlag Opt_DoStgLinting))
972   ,  ( "dcmm-lint",              NoArg (setDynFlag Opt_DoCmmLinting))
973   ,  ( "dshow-passes",           NoArg (do setDynFlag Opt_ForceRecomp
974                                            setVerbosity (Just 2)) )
975   ,  ( "dfaststring-stats",      NoArg (setDynFlag Opt_D_faststring_stats))
976
977         ------ Machine dependant (-m<blah>) stuff ---------------------------
978
979   ,  ( "monly-2-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
980   ,  ( "monly-3-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
981   ,  ( "monly-4-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
982
983         ------ Warning opts -------------------------------------------------
984   ,  ( "W"              , NoArg (mapM_ setDynFlag   minusWOpts)    )
985   ,  ( "Werror"         , NoArg (setDynFlag         Opt_WarnIsError) )
986   ,  ( "Wall"           , NoArg (mapM_ setDynFlag   minusWallOpts) )
987   ,  ( "Wnot"           , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
988   ,  ( "w"              , NoArg (mapM_ unSetDynFlag minusWallOpts) )
989
990         ------ Optimisation flags ------------------------------------------
991   ,  ( "O"      , NoArg (upd (setOptLevel 1)))
992   ,  ( "Onot"   , NoArg (upd (setOptLevel 0)))
993   ,  ( "O"      , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
994                 -- If the number is missing, use 1
995
996   ,  ( "fmax-simplifier-iterations", IntSuffix (\n -> 
997                 upd (\dfs -> dfs{ maxSimplIterations = n })) )
998   ,  ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ libCaseThreshold = n })))
999   ,  ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1000   ,  ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1001
1002         ------ Compiler flags -----------------------------------------------
1003
1004   ,  ( "fno-code",      NoArg (setTarget HscNothing))
1005   ,  ( "fasm",          AnySuffix (\_ -> setTarget HscAsm) )
1006   ,  ( "fvia-c",        NoArg (setTarget HscC) )
1007   ,  ( "fvia-C",        NoArg (setTarget HscC) )
1008
1009   ,  ( "fglasgow-exts",    NoArg (mapM_ setDynFlag   glasgowExtsFlags) )
1010   ,  ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1011
1012
1013         -- the rest of the -f* and -fno-* flags
1014   ,  ( "fno-",          PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
1015   ,  ( "f",             PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
1016  ]
1017
1018 -- these -f<blah> flags can all be reversed with -fno-<blah>
1019
1020 fFlags = [
1021   ( "warn-duplicate-exports",           Opt_WarnDuplicateExports ),
1022   ( "warn-hi-shadowing",                Opt_WarnHiShadows ),
1023   ( "warn-incomplete-patterns",         Opt_WarnIncompletePatterns ),
1024   ( "warn-incomplete-record-updates",   Opt_WarnIncompletePatternsRecUpd ),
1025   ( "warn-missing-fields",              Opt_WarnMissingFields ),
1026   ( "warn-missing-methods",             Opt_WarnMissingMethods ),
1027   ( "warn-missing-signatures",          Opt_WarnMissingSigs ),
1028   ( "warn-name-shadowing",              Opt_WarnNameShadowing ),
1029   ( "warn-overlapping-patterns",        Opt_WarnOverlappingPatterns ),
1030   ( "warn-simple-patterns",             Opt_WarnSimplePatterns ),
1031   ( "warn-type-defaults",               Opt_WarnTypeDefaults ),
1032   ( "warn-unused-binds",                Opt_WarnUnusedBinds ),
1033   ( "warn-unused-imports",              Opt_WarnUnusedImports ),
1034   ( "warn-unused-matches",              Opt_WarnUnusedMatches ),
1035   ( "warn-deprecations",                Opt_WarnDeprecations ),
1036   ( "warn-orphans",                     Opt_WarnOrphans ),
1037   ( "warn-tabs",                        Opt_WarnTabs ),
1038   ( "fi",                               Opt_FFI ),  -- support `-ffi'...
1039   ( "ffi",                              Opt_FFI ),  -- ...and also `-fffi'
1040   ( "arrows",                           Opt_Arrows ), -- arrow syntax
1041   ( "parr",                             Opt_PArr ),
1042   ( "th",                               Opt_TH ),
1043   ( "implicit-prelude",                 Opt_ImplicitPrelude ),
1044   ( "scoped-type-variables",            Opt_ScopedTypeVariables ),
1045   ( "bang-patterns",                    Opt_BangPatterns ),
1046   ( "overloaded-strings",               Opt_OverloadedStrings ),
1047   ( "indexed-types",                    Opt_IndexedTypes ),
1048   ( "monomorphism-restriction",         Opt_MonomorphismRestriction ),
1049   ( "mono-pat-binds",                   Opt_MonoPatBinds ),
1050   ( "extended-default-rules",           Opt_ExtendedDefaultRules ),
1051   ( "implicit-params",                  Opt_ImplicitParams ),
1052   ( "allow-overlapping-instances",      Opt_AllowOverlappingInstances ),
1053   ( "allow-undecidable-instances",      Opt_AllowUndecidableInstances ),
1054   ( "allow-incoherent-instances",       Opt_AllowIncoherentInstances ),
1055   ( "generics",                         Opt_Generics ),
1056   ( "strictness",                       Opt_Strictness ),
1057   ( "full-laziness",                    Opt_FullLaziness ),
1058   ( "cse",                              Opt_CSE ),
1059   ( "ignore-interface-pragmas",         Opt_IgnoreInterfacePragmas ),
1060   ( "omit-interface-pragmas",           Opt_OmitInterfacePragmas ),
1061   ( "do-lambda-eta-expansion",          Opt_DoLambdaEtaExpansion ),
1062   ( "ignore-asserts",                   Opt_IgnoreAsserts ),
1063   ( "ignore-breakpoints",               Opt_IgnoreBreakpoints),
1064   ( "do-eta-reduction",                 Opt_DoEtaReduction ),
1065   ( "case-merge",                       Opt_CaseMerge ),
1066   ( "unbox-strict-fields",              Opt_UnboxStrictFields ),
1067   ( "dicts-cheap",                      Opt_DictsCheap ),
1068   ( "excess-precision",                 Opt_ExcessPrecision ),
1069   ( "asm-mangling",                     Opt_DoAsmMangling ),
1070   ( "print-bind-result",                Opt_PrintBindResult ),
1071 #if defined(GHCI) && defined(DEBUGGER)
1072   ( "debugging",                        Opt_Debugging),
1073 #endif
1074   ( "force-recomp",                     Opt_ForceRecomp ),
1075   ( "hpc-no-auto",                      Opt_Hpc_No_Auto )
1076   ]
1077
1078
1079 glasgowExtsFlags = [ 
1080   Opt_GlasgowExts, 
1081   Opt_FFI, 
1082   Opt_ImplicitParams, 
1083   Opt_ScopedTypeVariables,
1084   Opt_IndexedTypes ]
1085
1086 isFFlag f = f `elem` (map fst fFlags)
1087 getFFlag f = fromJust (lookup f fFlags)
1088
1089 -- -----------------------------------------------------------------------------
1090 -- Parsing the dynamic flags.
1091
1092 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1093 parseDynamicFlags dflags args = do
1094   let ((leftover,errs),dflags') 
1095           = runCmdLine (processArgs dynamic_flags args) dflags
1096   when (not (null errs)) $ do
1097     throwDyn (UsageError (unlines errs))
1098   return (dflags', leftover)
1099
1100
1101 type DynP = CmdLineP DynFlags
1102
1103 upd :: (DynFlags -> DynFlags) -> DynP ()
1104 upd f = do 
1105    dfs <- getCmdLineState
1106    putCmdLineState $! (f dfs)
1107
1108 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1109 setDynFlag f   = upd (\dfs -> dopt_set dfs f)
1110 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1111
1112 setDumpFlag :: DynFlag -> OptKind DynP
1113 setDumpFlag dump_flag 
1114   = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1115         -- Whenver we -ddump, switch off the recompilation checker,
1116         -- else you don't see the dump!
1117
1118 setVerbosity :: Maybe Int -> DynP ()
1119 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1120
1121 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes =  a : cmdlineHcIncludes s})
1122
1123 extraPkgConf_  p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1124
1125 exposePackage p = 
1126   upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1127 hidePackage p = 
1128   upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1129 ignorePackage p = 
1130   upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1131
1132 setPackageName p
1133   | Nothing <- unpackPackageId pid
1134   = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1135   | otherwise
1136   = \s -> s{ thisPackage = pid }
1137   where
1138         pid = stringToPackageId p
1139
1140 -- we can only switch between HscC, and HscAsmm with dynamic flags 
1141 -- (-fvia-C, -fasm, -filx respectively).
1142 setTarget l = upd (\dfs -> case hscTarget dfs of
1143                                         HscC   -> dfs{ hscTarget = l }
1144                                         HscAsm -> dfs{ hscTarget = l }
1145                                         _      -> dfs)
1146
1147 setOptLevel :: Int -> DynFlags -> DynFlags
1148 setOptLevel n dflags
1149    | hscTarget dflags == HscInterpreted && n > 0
1150         = dflags
1151             -- not in IO any more, oh well:
1152             -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1153    | otherwise
1154         = updOptLevel n dflags
1155
1156
1157 setMainIs :: String -> DynP ()
1158 setMainIs arg
1159   | not (null main_fn)          -- The arg looked like "Foo.baz"
1160   = upd $ \d -> d{ mainFunIs = Just main_fn,
1161                    mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1162
1163   | isUpper (head main_mod)     -- The arg looked like "Foo"
1164   = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1165   
1166   | otherwise                   -- The arg looked like "baz"
1167   = upd $ \d -> d{ mainFunIs = Just main_mod }
1168   where
1169     (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1170
1171 -----------------------------------------------------------------------------
1172 -- Paths & Libraries
1173
1174 -- -i on its own deletes the import paths
1175 addImportPath "" = upd (\s -> s{importPaths = []})
1176 addImportPath p  = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1177
1178
1179 addLibraryPath p = 
1180   upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1181
1182 addIncludePath p = 
1183   upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1184
1185 addFrameworkPath p = 
1186   upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1187
1188 split_marker = ':'   -- not configurable (ToDo)
1189
1190 splitPathList :: String -> [String]
1191 splitPathList s = filter notNull (splitUp s)
1192                 -- empty paths are ignored: there might be a trailing
1193                 -- ':' in the initial list, for example.  Empty paths can
1194                 -- cause confusion when they are translated into -I options
1195                 -- for passing to gcc.
1196   where
1197 #ifndef mingw32_TARGET_OS
1198     splitUp xs = split split_marker xs
1199 #else 
1200      -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1201      -- 
1202      -- That is, if "foo:bar:baz" is used, this interpreted as
1203      -- consisting of three entries, 'foo', 'bar', 'baz'.
1204      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1205      -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1206      --
1207      -- Notice that no attempt is made to fully replace the 'standard'
1208      -- split marker ':' with the Windows / DOS one, ';'. The reason being
1209      -- that this will cause too much breakage for users & ':' will
1210      -- work fine even with DOS paths, if you're not insisting on being silly.
1211      -- So, use either.
1212     splitUp []             = []
1213     splitUp (x:':':div:xs) | div `elem` dir_markers
1214                            = ((x:':':div:p): splitUp rs)
1215                            where
1216                               (p,rs) = findNextPath xs
1217           -- we used to check for existence of the path here, but that
1218           -- required the IO monad to be threaded through the command-line
1219           -- parser which is quite inconvenient.  The 
1220     splitUp xs = cons p (splitUp rs)
1221                where
1222                  (p,rs) = findNextPath xs
1223     
1224                  cons "" xs = xs
1225                  cons x  xs = x:xs
1226
1227     -- will be called either when we've consumed nought or the
1228     -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1229     -- finding the next split marker.
1230     findNextPath xs = 
1231         case break (`elem` split_markers) xs of
1232            (p, d:ds) -> (p, ds)
1233            (p, xs)   -> (p, xs)
1234
1235     split_markers :: [Char]
1236     split_markers = [':', ';']
1237
1238     dir_markers :: [Char]
1239     dir_markers = ['/', '\\']
1240 #endif
1241
1242 -- -----------------------------------------------------------------------------
1243 -- tmpDir, where we store temporary files.
1244
1245 setTmpDir :: FilePath -> DynFlags -> DynFlags
1246 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1247   where
1248 #if !defined(mingw32_HOST_OS)
1249      canonicalise p = normalisePath p
1250 #else
1251         -- Canonicalisation of temp path under win32 is a bit more
1252         -- involved: (a) strip trailing slash, 
1253         --           (b) normalise slashes
1254         --           (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1255         -- 
1256      canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1257
1258         -- if we're operating under cygwin, and TMP/TEMP is of
1259         -- the form "/cygdrive/drive/path", translate this to
1260         -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1261         -- understand /cygdrive paths.)
1262      xltCygdrive path
1263       | "/cygdrive/" `isPrefixOf` path = 
1264           case drop (length "/cygdrive/") path of
1265             drive:xs@('/':_) -> drive:':':xs
1266             _ -> path
1267       | otherwise = path
1268
1269         -- strip the trailing backslash (awful, but we only do this once).
1270      removeTrailingSlash path = 
1271        case last path of
1272          '/'  -> init path
1273          '\\' -> init path
1274          _    -> path
1275 #endif
1276
1277 -----------------------------------------------------------------------------
1278 -- Hpc stuff
1279
1280 setOptHpcDir :: String -> DynP ()
1281 setOptHpcDir arg  = upd $ \ d -> d{hpcDir = arg}
1282
1283 -----------------------------------------------------------------------------
1284 -- Via-C compilation stuff
1285
1286 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1287                               [String]) -- for registerised HC compilations
1288 machdepCCOpts dflags
1289 #if alpha_TARGET_ARCH
1290         =       ( ["-w", "-mieee"
1291 #ifdef HAVE_THREADED_RTS_SUPPORT
1292                     , "-D_REENTRANT"
1293 #endif
1294                    ], [] )
1295         -- For now, to suppress the gcc warning "call-clobbered
1296         -- register used for global register variable", we simply
1297         -- disable all warnings altogether using the -w flag. Oh well.
1298
1299 #elif hppa_TARGET_ARCH
1300         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1301         -- (very nice, but too bad the HP /usr/include files don't agree.)
1302         = ( ["-D_HPUX_SOURCE"], [] )
1303
1304 #elif m68k_TARGET_ARCH
1305       -- -fno-defer-pop : for the .hc files, we want all the pushing/
1306       --    popping of args to routines to be explicit; if we let things
1307       --    be deferred 'til after an STGJUMP, imminent death is certain!
1308       --
1309       -- -fomit-frame-pointer : *don't*
1310       --     It's better to have a6 completely tied up being a frame pointer
1311       --     rather than let GCC pick random things to do with it.
1312       --     (If we want to steal a6, then we would try to do things
1313       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
1314         = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1315
1316 #elif i386_TARGET_ARCH
1317       -- -fno-defer-pop : basically the same game as for m68k
1318       --
1319       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1320       --   the fp (%ebp) for our register maps.
1321         =  let n_regs = stolen_x86_regs dflags
1322                sta = opt_Static
1323            in
1324                     ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1325 --                    , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else "" 
1326                       ],
1327                       [ "-fno-defer-pop",
1328 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1329                         -- Some gccs are configured with
1330                         -- -momit-leaf-frame-pointer on by default, and it
1331                         -- apparently takes precedence over 
1332                         -- -fomit-frame-pointer, so we disable it first here.
1333                         "-mno-omit-leaf-frame-pointer",
1334 #endif
1335 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1336                         "-fno-unit-at-a-time",
1337                         -- unit-at-a-time doesn't do us any good, and screws
1338                         -- up -split-objs by moving the split markers around.
1339                         -- It's only turned on with -O2, but put it here just
1340                         -- in case someone uses -optc-O2.
1341 #endif
1342                         "-fomit-frame-pointer",
1343                         -- we want -fno-builtin, because when gcc inlines
1344                         -- built-in functions like memcpy() it tends to
1345                         -- run out of registers, requiring -monly-n-regs
1346                         "-fno-builtin",
1347                         "-DSTOLEN_X86_REGS="++show n_regs ]
1348                     )
1349
1350 #elif ia64_TARGET_ARCH
1351         = ( [], ["-fomit-frame-pointer", "-G0"] )
1352
1353 #elif x86_64_TARGET_ARCH
1354         = ( [], ["-fomit-frame-pointer",
1355                  "-fno-asynchronous-unwind-tables",
1356                         -- the unwind tables are unnecessary for HC code,
1357                         -- and get in the way of -split-objs.  Another option
1358                         -- would be to throw them away in the mangler, but this
1359                         -- is easier.
1360 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1361                  "-fno-unit-at-a-time",
1362                         -- unit-at-a-time doesn't do us any good, and screws
1363                         -- up -split-objs by moving the split markers around.
1364                         -- It's only turned on with -O2, but put it here just
1365                         -- in case someone uses -optc-O2.
1366 #endif
1367                  "-fno-builtin"
1368                         -- calling builtins like strlen() using the FFI can
1369                         -- cause gcc to run out of regs, so use the external
1370                         -- version.
1371                 ] )
1372
1373 #elif sparc_TARGET_ARCH
1374         = ( [], ["-w"] )
1375         -- For now, to suppress the gcc warning "call-clobbered
1376         -- register used for global register variable", we simply
1377         -- disable all warnings altogether using the -w flag. Oh well.
1378
1379 #elif powerpc_apple_darwin_TARGET
1380       -- -no-cpp-precomp:
1381       --     Disable Apple's precompiling preprocessor. It's a great thing
1382       --     for "normal" programs, but it doesn't support register variable
1383       --     declarations.
1384         = ( [], ["-no-cpp-precomp"] )
1385 #else
1386         = ( [], [] )
1387 #endif
1388
1389 picCCOpts :: DynFlags -> [String]
1390 picCCOpts dflags
1391 #if darwin_TARGET_OS
1392       -- Apple prefers to do things the other way round.
1393       -- PIC is on by default.
1394       -- -mdynamic-no-pic:
1395       --     Turn off PIC code generation.
1396       -- -fno-common:
1397       --     Don't generate "common" symbols - these are unwanted
1398       --     in dynamic libraries.
1399
1400     | opt_PIC
1401         = ["-fno-common"]
1402     | otherwise
1403         = ["-mdynamic-no-pic"]
1404 #elif mingw32_TARGET_OS
1405       -- no -fPIC for Windows
1406         = []
1407 #else
1408     | opt_PIC
1409         = ["-fPIC"]
1410     | otherwise
1411         = []
1412 #endif
1413
1414 -- -----------------------------------------------------------------------------
1415 -- Splitting
1416
1417 can_split :: Bool
1418 can_split =  
1419 #if    defined(i386_TARGET_ARCH)     \
1420     || defined(x86_64_TARGET_ARCH)   \
1421     || defined(alpha_TARGET_ARCH)    \
1422     || defined(hppa_TARGET_ARCH)     \
1423     || defined(m68k_TARGET_ARCH)     \
1424     || defined(mips_TARGET_ARCH)     \
1425     || defined(powerpc_TARGET_ARCH)  \
1426     || defined(rs6000_TARGET_ARCH)   \
1427     || defined(sparc_TARGET_ARCH) 
1428    True
1429 #else
1430    False
1431 #endif
1432