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