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