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