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