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