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