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