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