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