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