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