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