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