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