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