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