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