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