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