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