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