3ef66cb0998134a925898e6fbc9d20d87e236484
[ghc-hetmet.git] / compiler / main / DynFlags.hs
1
2 {-# OPTIONS -fno-warn-missing-fields #-}
3 {-# OPTIONS -w #-}
4 -- The above warning supression flag is a temporary kludge.
5 -- While working on this module you are encouraged to remove it and fix
6 -- any warnings in the module. See
7 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
8 -- for details
9
10 -----------------------------------------------------------------------------
11 --
12 -- Dynamic flags
13 --
14 -- Most flags are dynamic flags, which means they can change from
15 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
16 -- multi-session GHC each session can be using different dynamic
17 -- flags.  Dynamic flags can also be set at the prompt in GHCi.
18 --
19 -- (c) The University of Glasgow 2005
20 --
21 -----------------------------------------------------------------------------
22
23 module DynFlags (
24         -- Dynamic flags
25         DynFlag(..),
26         DynFlags(..),
27         HscTarget(..), isObjectTarget, defaultObjectTarget,
28         GhcMode(..), isOneShot,
29         GhcLink(..), isNoLink,
30         PackageFlag(..),
31         Option(..),
32         fFlags, xFlags,
33
34         -- Configuration of the core-to-core and stg-to-stg phases
35         CoreToDo(..),
36         StgToDo(..),
37         SimplifierSwitch(..), 
38         SimplifierMode(..), FloatOutSwitches(..),
39         getCoreToDo, getStgToDo,
40         
41         -- Manipulating DynFlags
42         defaultDynFlags,                -- DynFlags
43         initDynFlags,                   -- DynFlags -> IO DynFlags
44
45         dopt,                           -- DynFlag -> DynFlags -> Bool
46         dopt_set, dopt_unset,           -- DynFlags -> DynFlag -> DynFlags
47         getOpts,                        -- (DynFlags -> [a]) -> IO [a]
48         getVerbFlag,
49         updOptLevel,
50         setTmpDir,
51         setPackageName,
52         
53         -- parsing DynFlags
54         parseDynamicFlags,
55         allFlags,
56
57         -- misc stuff
58         machdepCCOpts, picCCOpts,
59     supportedLanguages,
60     compilerInfo,
61   ) where
62
63 #include "HsVersions.h"
64
65 import Module
66 import PackageConfig
67 import PrelNames        ( mAIN )
68 #ifdef i386_TARGET_ARCH
69 import StaticFlags      ( opt_Static )
70 #endif
71 import StaticFlags      ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
72                           v_RTS_Build_tag )
73 import {-# SOURCE #-} Packages (PackageState)
74 import DriverPhases     ( Phase(..), phaseInputExt )
75 import Config
76 import CmdLineParser
77 import Constants        ( mAX_CONTEXT_REDUCTION_DEPTH )
78 import Panic            ( panic, GhcException(..) )
79 import UniqFM           ( UniqFM )
80 import Util
81 import Maybes           ( orElse, fromJust )
82 import SrcLoc           ( SrcSpan )
83 import Outputable
84 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
85
86 import Data.IORef       ( readIORef )
87 import Control.Exception ( throwDyn )
88 import Control.Monad    ( when )
89 #ifdef mingw32_TARGET_OS
90 import Data.List        ( isPrefixOf )
91 #else
92 import Util             ( split )
93 #endif
94
95 import Data.Char
96 import System.IO        ( hPutStrLn, stderr )
97
98 -- -----------------------------------------------------------------------------
99 -- DynFlags
100
101 data DynFlag
102
103    -- debugging flags
104    = Opt_D_dump_cmm
105    | Opt_D_dump_cmmz
106    | Opt_D_dump_cmmz_pretty
107    | Opt_D_dump_cps_cmm
108    | Opt_D_dump_cvt_cmm
109    | Opt_D_dump_asm
110    | Opt_D_dump_asm_native
111    | Opt_D_dump_asm_liveness
112    | Opt_D_dump_asm_coalesce
113    | Opt_D_dump_asm_regalloc
114    | Opt_D_dump_asm_regalloc_stages
115    | Opt_D_dump_asm_conflicts
116    | Opt_D_dump_asm_stats
117    | Opt_D_dump_cpranal
118    | Opt_D_dump_deriv
119    | Opt_D_dump_ds
120    | Opt_D_dump_flatC
121    | Opt_D_dump_foreign
122    | Opt_D_dump_inlinings
123    | Opt_D_dump_rule_firings
124    | Opt_D_dump_occur_anal
125    | Opt_D_dump_parsed
126    | Opt_D_dump_rn
127    | Opt_D_dump_simpl
128    | Opt_D_dump_simpl_iterations
129    | Opt_D_dump_spec
130    | Opt_D_dump_prep
131    | Opt_D_dump_stg
132    | Opt_D_dump_stranal
133    | Opt_D_dump_tc
134    | Opt_D_dump_types
135    | Opt_D_dump_rules
136    | Opt_D_dump_cse
137    | Opt_D_dump_worker_wrapper
138    | Opt_D_dump_rn_trace
139    | Opt_D_dump_rn_stats
140    | Opt_D_dump_opt_cmm
141    | Opt_D_dump_simpl_stats
142    | Opt_D_dump_tc_trace
143    | Opt_D_dump_if_trace
144    | Opt_D_dump_splices
145    | Opt_D_dump_BCOs
146    | Opt_D_dump_vect
147    | Opt_D_dump_hpc
148    | Opt_D_source_stats
149    | Opt_D_verbose_core2core
150    | Opt_D_verbose_stg2stg
151    | Opt_D_dump_hi
152    | Opt_D_dump_hi_diffs
153    | Opt_D_dump_minimal_imports
154    | Opt_D_dump_mod_cycles
155    | Opt_D_dump_view_pattern_commoning
156    | Opt_D_faststring_stats
157    | Opt_DumpToFile                     -- ^ Append dump output to files instead of stdout.
158    | Opt_DoCoreLinting
159    | Opt_DoStgLinting
160    | Opt_DoCmmLinting
161    | Opt_DoAsmLinting
162
163    | Opt_WarnIsError                    -- -Werror; makes warnings fatal
164    | Opt_WarnDuplicateExports
165    | Opt_WarnHiShadows
166    | Opt_WarnImplicitPrelude
167    | Opt_WarnIncompletePatterns
168    | Opt_WarnIncompletePatternsRecUpd
169    | Opt_WarnMissingFields
170    | Opt_WarnMissingMethods
171    | Opt_WarnMissingSigs
172    | Opt_WarnNameShadowing
173    | Opt_WarnOverlappingPatterns
174    | Opt_WarnSimplePatterns
175    | Opt_WarnTypeDefaults
176    | Opt_WarnMonomorphism
177    | Opt_WarnUnusedBinds
178    | Opt_WarnUnusedImports
179    | Opt_WarnUnusedMatches
180    | Opt_WarnDeprecations
181    | Opt_WarnDodgyImports
182    | Opt_WarnOrphans
183    | Opt_WarnTabs
184
185    -- language opts
186    | Opt_OverlappingInstances
187    | Opt_UndecidableInstances
188    | Opt_IncoherentInstances
189    | Opt_MonomorphismRestriction
190    | Opt_MonoPatBinds
191    | Opt_ExtendedDefaultRules           -- Use GHC's extended rules for defaulting
192    | Opt_ForeignFunctionInterface
193    | Opt_UnliftedFFITypes
194    | Opt_PArr                           -- Syntactic support for parallel arrays
195    | Opt_Arrows                         -- Arrow-notation syntax
196    | Opt_TemplateHaskell
197    | Opt_ImplicitParams
198    | Opt_Generics
199    | Opt_ImplicitPrelude 
200    | Opt_ScopedTypeVariables
201    | Opt_UnboxedTuples
202    | Opt_BangPatterns
203    | Opt_TypeFamilies
204    | Opt_OverloadedStrings
205    | Opt_DisambiguateRecordFields
206    | Opt_RecordWildCards
207    | Opt_RecordPuns
208    | Opt_ViewPatterns
209    | Opt_GADTs
210    | Opt_RelaxedPolyRec
211    | Opt_StandaloneDeriving
212    | Opt_DeriveDataTypeable
213    | Opt_TypeSynonymInstances
214    | Opt_FlexibleContexts
215    | Opt_FlexibleInstances
216    | Opt_ConstrainedClassMethods
217    | Opt_MultiParamTypeClasses
218    | Opt_FunctionalDependencies
219    | Opt_UnicodeSyntax
220    | Opt_PolymorphicComponents
221    | Opt_ExistentialQuantification
222    | Opt_MagicHash
223    | Opt_EmptyDataDecls
224    | Opt_KindSignatures
225    | Opt_PatternSignatures
226    | Opt_ParallelListComp
227    | Opt_GeneralizedNewtypeDeriving
228    | Opt_RecursiveDo
229    | Opt_PatternGuards
230    | Opt_LiberalTypeSynonyms
231    | Opt_Rank2Types
232    | Opt_RankNTypes
233    | Opt_TypeOperators
234
235    | Opt_PrintExplicitForalls
236
237    -- optimisation opts
238    | Opt_Strictness
239    | Opt_FullLaziness
240    | Opt_CSE
241    | Opt_LiberateCase
242    | Opt_SpecConstr
243    | Opt_IgnoreInterfacePragmas
244    | Opt_OmitInterfacePragmas
245    | Opt_DoLambdaEtaExpansion
246    | Opt_IgnoreAsserts
247    | Opt_IgnoreBreakpoints
248    | Opt_DoEtaReduction
249    | Opt_CaseMerge
250    | Opt_UnboxStrictFields
251    | Opt_DictsCheap
252    | Opt_RewriteRules
253    | Opt_Vectorise
254    | Opt_RegsGraph                      -- do graph coloring register allocation
255    | Opt_RegsIterative                  -- do iterative coalescing graph coloring register allocation
256
257    -- misc opts
258    | Opt_Cpp
259    | Opt_Pp
260    | Opt_ForceRecomp
261    | Opt_DryRun
262    | Opt_DoAsmMangling
263    | Opt_ExcessPrecision
264    | Opt_ReadUserPackageConf
265    | Opt_NoHsMain
266    | Opt_SplitObjs
267    | Opt_StgStats
268    | Opt_HideAllPackages
269    | Opt_PrintBindResult
270    | Opt_Haddock
271    | Opt_HaddockOptions
272    | Opt_Hpc_No_Auto
273    | Opt_BreakOnException
274    | Opt_BreakOnError
275    | Opt_PrintEvldWithShow
276    | Opt_GenManifest
277    | Opt_EmbedManifest
278    | Opt_RunCPSZ
279    | Opt_ConvertToZipCfgAndBack
280
281    -- keeping stuff
282    | Opt_KeepHiDiffs
283    | Opt_KeepHcFiles
284    | Opt_KeepSFiles
285    | Opt_KeepRawSFiles
286    | Opt_KeepTmpFiles
287
288    deriving (Eq, Show)
289  
290 data DynFlags = DynFlags {
291   ghcMode               :: GhcMode,
292   ghcLink               :: GhcLink,
293   coreToDo              :: Maybe [CoreToDo], -- reserved for -Ofile
294   stgToDo               :: Maybe [StgToDo],  -- similarly
295   hscTarget             :: HscTarget,
296   hscOutName            :: String,      -- name of the output file
297   extCoreName           :: String,      -- name of the .core output file
298   verbosity             :: Int,         -- verbosity level
299   optLevel              :: Int,         -- optimisation level
300   maxSimplIterations    :: Int,         -- max simplifier iterations
301   ruleCheck             :: Maybe String,
302
303   specThreshold         :: Int,         -- Threshold for function specialisation
304
305   stolen_x86_regs       :: Int,         
306   cmdlineHcIncludes     :: [String],    -- -#includes
307   importPaths           :: [FilePath],
308   mainModIs             :: Module,
309   mainFunIs             :: Maybe String,
310   ctxtStkDepth          :: Int,         -- Typechecker context stack depth
311
312   thisPackage           :: PackageId,
313
314   -- ways
315   wayNames              :: [WayName],   -- way flags from the cmd line
316   buildTag              :: String,      -- the global "way" (eg. "p" for prof)
317   rtsBuildTag           :: String,      -- the RTS "way"
318   
319   -- paths etc.
320   objectDir             :: Maybe String,
321   hiDir                 :: Maybe String,
322   stubDir               :: Maybe String,
323
324   objectSuf             :: String,
325   hcSuf                 :: String,
326   hiSuf                 :: String,
327
328   outputFile            :: Maybe String,
329   outputHi              :: Maybe String,
330
331   -- | This is set by DriverPipeline.runPipeline based on where
332   --    its output is going.
333   dumpPrefix            :: Maybe FilePath,
334
335   -- | Override the dumpPrefix set by runPipeline.
336   --    Set by -ddump-file-prefix
337   dumpPrefixForce       :: Maybe FilePath,
338
339   includePaths          :: [String],
340   libraryPaths          :: [String],
341   frameworkPaths        :: [String],    -- used on darwin only
342   cmdlineFrameworks     :: [String],    -- ditto
343   tmpDir                :: String,      -- no trailing '/'
344   
345   ghcUsagePath          :: FilePath,    -- Filled in by SysTools
346   ghciUsagePath         :: FilePath,    -- ditto
347
348   hpcDir                :: String,      -- ^ path to store the .mix files
349
350   -- options for particular phases
351   opt_L                 :: [String],
352   opt_P                 :: [String],
353   opt_F                 :: [String],
354   opt_c                 :: [String],
355   opt_m                 :: [String],
356   opt_a                 :: [String],
357   opt_l                 :: [String],
358   opt_dep               :: [String],
359   opt_windres           :: [String],
360
361   -- commands for particular phases
362   pgm_L                 :: String,
363   pgm_P                 :: (String,[Option]),
364   pgm_F                 :: String,
365   pgm_c                 :: (String,[Option]),
366   pgm_m                 :: (String,[Option]),
367   pgm_s                 :: (String,[Option]),
368   pgm_a                 :: (String,[Option]),
369   pgm_l                 :: (String,[Option]),
370   pgm_dll               :: (String,[Option]),
371   pgm_T                 :: String,
372   pgm_sysman            :: String,
373   pgm_windres           :: String,
374
375   --  Package flags
376   extraPkgConfs         :: [FilePath],
377   topDir                :: FilePath,    -- filled in by SysTools
378   systemPackageConfig   :: FilePath,    -- ditto
379         -- The -package-conf flags given on the command line, in the order
380         -- they appeared.
381
382   packageFlags          :: [PackageFlag],
383         -- The -package and -hide-package flags from the command-line
384
385   -- Package state
386   -- NB. do not modify this field, it is calculated by 
387   -- Packages.initPackages and Packages.updatePackages.
388   pkgDatabase           :: Maybe (UniqFM PackageConfig),
389   pkgState              :: PackageState,
390
391   -- hsc dynamic flags
392   flags                 :: [DynFlag],
393   
394   -- message output
395   log_action            :: Severity -> SrcSpan -> PprStyle -> Message -> IO (),
396
397   haddockOptions :: Maybe String
398  }
399
400 data HscTarget
401   = HscC
402   | HscAsm
403   | HscJava
404   | HscInterpreted
405   | HscNothing
406   deriving (Eq, Show)
407
408 -- | will this target result in an object file on the disk?
409 isObjectTarget :: HscTarget -> Bool
410 isObjectTarget HscC     = True
411 isObjectTarget HscAsm   = True
412 isObjectTarget _        = False
413
414 -- | The 'GhcMode' tells us whether we're doing multi-module
415 -- compilation (controlled via the "GHC" API) or one-shot
416 -- (single-module) compilation.  This makes a difference primarily to
417 -- the "Finder": in one-shot mode we look for interface files for
418 -- imported modules, but in multi-module mode we look for source files
419 -- in order to check whether they need to be recompiled.
420 data GhcMode
421   = CompManager         -- ^ --make, GHCi, etc.
422   | OneShot             -- ^ ghc -c Foo.hs
423   | MkDepend            -- ^ ghc -M, see Finder for why we need this
424   deriving Eq
425
426 isOneShot :: GhcMode -> Bool
427 isOneShot OneShot = True
428 isOneShot _other  = False
429
430 -- | What kind of linking to do.
431 data GhcLink    -- What to do in the link step, if there is one
432   = NoLink              -- Don't link at all
433   | LinkBinary          -- Link object code into a binary
434   | LinkInMemory        -- Use the in-memory dynamic linker
435   | LinkDynLib          -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
436   deriving Eq
437
438 isNoLink :: GhcLink -> Bool
439 isNoLink NoLink = True
440 isNoLink other  = False
441
442 data PackageFlag
443   = ExposePackage  String
444   | HidePackage    String
445   | IgnorePackage  String
446   deriving Eq
447
448 defaultHscTarget = defaultObjectTarget
449
450 -- | the 'HscTarget' value corresponding to the default way to create
451 -- object files on the current platform.
452 defaultObjectTarget
453   | cGhcWithNativeCodeGen == "YES"      =  HscAsm
454   | otherwise                           =  HscC
455
456 initDynFlags dflags = do
457  -- someday these will be dynamic flags
458  ways <- readIORef v_Ways
459  build_tag <- readIORef v_Build_tag
460  rts_build_tag <- readIORef v_RTS_Build_tag
461  return dflags{
462         wayNames        = ways,
463         buildTag        = build_tag,
464         rtsBuildTag     = rts_build_tag
465         }
466
467 defaultDynFlags =
468      DynFlags {
469         ghcMode                 = CompManager,
470         ghcLink                 = LinkBinary,
471         coreToDo                = Nothing,
472         stgToDo                 = Nothing, 
473         hscTarget               = defaultHscTarget, 
474         hscOutName              = "", 
475         extCoreName             = "",
476         verbosity               = 0, 
477         optLevel                = 0,
478         maxSimplIterations      = 4,
479         ruleCheck               = Nothing,
480         specThreshold           = 200,
481         stolen_x86_regs         = 4,
482         cmdlineHcIncludes       = [],
483         importPaths             = ["."],
484         mainModIs               = mAIN,
485         mainFunIs               = Nothing,
486         ctxtStkDepth            = mAX_CONTEXT_REDUCTION_DEPTH,
487
488         thisPackage             = mainPackageId,
489
490         objectDir               = Nothing,
491         hiDir                   = Nothing,
492         stubDir                 = Nothing,
493
494         objectSuf               = phaseInputExt StopLn,
495         hcSuf                   = phaseInputExt HCc,
496         hiSuf                   = "hi",
497
498         outputFile              = Nothing,
499         outputHi                = Nothing,
500         dumpPrefix              = Nothing,
501         dumpPrefixForce         = Nothing,
502         includePaths            = [],
503         libraryPaths            = [],
504         frameworkPaths          = [],
505         cmdlineFrameworks       = [],
506         tmpDir                  = cDEFAULT_TMPDIR,
507         
508         hpcDir                  = ".hpc",
509
510         opt_L                   = [],
511         opt_P                   = (if opt_PIC
512                                    then ["-D__PIC__"]
513                                    else []),
514         opt_F                   = [],
515         opt_c                   = [],
516         opt_a                   = [],
517         opt_m                   = [],
518         opt_l                   = [],
519         opt_dep                 = [],
520         opt_windres             = [],
521         
522         extraPkgConfs           = [],
523         packageFlags            = [],
524         pkgDatabase             = Nothing,
525         pkgState                = panic "no package state yet: call GHC.setSessionDynFlags",
526   haddockOptions = Nothing,
527         flags = [ 
528             Opt_ReadUserPackageConf,
529     
530             Opt_MonoPatBinds,   -- Experimentally, I'm making this non-standard
531                                 -- behaviour the default, to see if anyone notices
532                                 -- SLPJ July 06
533
534             Opt_ImplicitPrelude,
535             Opt_MonomorphismRestriction,
536
537             Opt_DoAsmMangling,
538     
539             Opt_GenManifest,
540             Opt_EmbedManifest,
541
542             -- on by default:
543             Opt_PrintBindResult ]
544             ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
545                     -- The default -O0 options
546             ++ standardWarnings,
547                
548         log_action = \severity srcSpan style msg -> 
549                         case severity of
550                           SevInfo  -> hPutStrLn stderr (show (msg style))
551                           SevFatal -> hPutStrLn stderr (show (msg style))
552                           _        -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
553       }
554
555 {- 
556     Verbosity levels:
557         
558     0   |   print errors & warnings only
559     1   |   minimal verbosity: print "compiling M ... done." for each module.
560     2   |   equivalent to -dshow-passes
561     3   |   equivalent to existing "ghc -v"
562     4   |   "ghc -v -ddump-most"
563     5   |   "ghc -v -ddump-all"
564 -}
565
566 dopt :: DynFlag -> DynFlags -> Bool
567 dopt f dflags  = f `elem` (flags dflags)
568
569 dopt_set :: DynFlags -> DynFlag -> DynFlags
570 dopt_set dfs f = dfs{ flags = f : flags dfs }
571
572 dopt_unset :: DynFlags -> DynFlag -> DynFlags
573 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
574
575 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
576 getOpts dflags opts = reverse (opts dflags)
577         -- We add to the options from the front, so we need to reverse the list
578
579 getVerbFlag :: DynFlags -> String
580 getVerbFlag dflags 
581   | verbosity dflags >= 3  = "-v" 
582   | otherwise =  ""
583
584 setObjectDir  f d = d{ objectDir  = Just f}
585 setHiDir      f d = d{ hiDir      = Just f}
586 setStubDir    f d = d{ stubDir    = Just f, includePaths = f : includePaths d }
587   -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
588   -- #included from the .hc file when compiling with -fvia-C.
589
590 setObjectSuf  f d = d{ objectSuf  = f}
591 setHiSuf      f d = d{ hiSuf      = f}
592 setHcSuf      f d = d{ hcSuf      = f}
593
594 setOutputFile f d = d{ outputFile = f}
595 setOutputHi   f d = d{ outputHi   = f}
596
597 setDumpPrefixForce f d = d { dumpPrefixForce = f}
598
599 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
600 -- Config.hs should really use Option.
601 setPgmP   f d = let (pgm:args) = words f in d{ pgm_P   = (pgm, map Option args)}
602
603 setPgmL   f d = d{ pgm_L   = f}
604 setPgmF   f d = d{ pgm_F   = f}
605 setPgmc   f d = d{ pgm_c   = (f,[])}
606 setPgmm   f d = d{ pgm_m   = (f,[])}
607 setPgms   f d = d{ pgm_s   = (f,[])}
608 setPgma   f d = d{ pgm_a   = (f,[])}
609 setPgml   f d = d{ pgm_l   = (f,[])}
610 setPgmdll f d = d{ pgm_dll = (f,[])}
611 setPgmwindres f d = d{ pgm_windres = f}
612
613 addOptL   f d = d{ opt_L   = f : opt_L d}
614 addOptP   f d = d{ opt_P   = f : opt_P d}
615 addOptF   f d = d{ opt_F   = f : opt_F d}
616 addOptc   f d = d{ opt_c   = f : opt_c d}
617 addOptm   f d = d{ opt_m   = f : opt_m d}
618 addOpta   f d = d{ opt_a   = f : opt_a d}
619 addOptl   f d = d{ opt_l   = f : opt_l d}
620 addOptdep f d = d{ opt_dep = f : opt_dep d}
621 addOptwindres f d = d{ opt_windres = f : opt_windres d}
622
623 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
624
625 addHaddockOpts f d = d{ haddockOptions = Just f}
626
627 -- -----------------------------------------------------------------------------
628 -- Command-line options
629
630 -- When invoking external tools as part of the compilation pipeline, we
631 -- pass these a sequence of options on the command-line. Rather than
632 -- just using a list of Strings, we use a type that allows us to distinguish
633 -- between filepaths and 'other stuff'. [The reason being, of course, that
634 -- this type gives us a handle on transforming filenames, and filenames only,
635 -- to whatever format they're expected to be on a particular platform.]
636
637 data Option
638  = FileOption -- an entry that _contains_ filename(s) / filepaths.
639               String  -- a non-filepath prefix that shouldn't be 
640                       -- transformed (e.g., "/out=")
641               String  -- the filepath/filename portion
642  | Option     String
643  
644 -----------------------------------------------------------------------------
645 -- Setting the optimisation level
646
647 updOptLevel :: Int -> DynFlags -> DynFlags
648 -- Set dynflags appropriate to the optimisation level
649 updOptLevel n dfs
650   = dfs2{ optLevel = final_n }
651   where
652    final_n = max 0 (min 2 n)    -- Clamp to 0 <= n <= 2
653    dfs1 = foldr (flip dopt_unset) dfs  remove_dopts
654    dfs2 = foldr (flip dopt_set)   dfs1 extra_dopts
655
656    extra_dopts  = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
657    remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
658         
659 optLevelFlags :: [([Int], DynFlag)]
660 optLevelFlags
661   = [ ([0],     Opt_IgnoreInterfacePragmas)
662     , ([0],     Opt_OmitInterfacePragmas)
663
664     , ([1,2],   Opt_IgnoreAsserts)
665     , ([1,2],   Opt_RewriteRules)       -- Off for -O0; see Note [Scoping for Builtin rules]
666                                         --              in PrelRules
667     , ([1,2],   Opt_DoEtaReduction)
668     , ([1,2],   Opt_CaseMerge)
669     , ([1,2],   Opt_Strictness)
670     , ([1,2],   Opt_CSE)
671     , ([1,2],   Opt_FullLaziness)
672
673     , ([2],     Opt_LiberateCase)
674     , ([2],     Opt_SpecConstr)
675
676     , ([0,1,2], Opt_DoLambdaEtaExpansion)
677                 -- This one is important for a tiresome reason:
678                 -- we want to make sure that the bindings for data 
679                 -- constructors are eta-expanded.  This is probably
680                 -- a good thing anyway, but it seems fragile.
681     ]
682
683 -- -----------------------------------------------------------------------------
684 -- Standard sets of warning options
685
686 standardWarnings
687     = [ Opt_WarnDeprecations,
688         Opt_WarnOverlappingPatterns,
689         Opt_WarnMissingFields,
690         Opt_WarnMissingMethods,
691         Opt_WarnDuplicateExports
692       ]
693
694 minusWOpts
695     = standardWarnings ++ 
696       [ Opt_WarnUnusedBinds,
697         Opt_WarnUnusedMatches,
698         Opt_WarnUnusedImports,
699         Opt_WarnIncompletePatterns,
700         Opt_WarnDodgyImports
701       ]
702
703 minusWallOpts
704     = minusWOpts ++
705       [ Opt_WarnTypeDefaults,
706         Opt_WarnNameShadowing,
707         Opt_WarnMissingSigs,
708         Opt_WarnHiShadows,
709         Opt_WarnOrphans
710       ]
711
712 -- minuswRemovesOpts should be every warning option
713 minuswRemovesOpts
714     = minusWallOpts ++
715       [Opt_WarnImplicitPrelude,
716        Opt_WarnIncompletePatternsRecUpd,
717        Opt_WarnSimplePatterns,
718        Opt_WarnMonomorphism,
719        Opt_WarnTabs
720       ]
721
722 -- -----------------------------------------------------------------------------
723 -- CoreToDo:  abstraction of core-to-core passes to run.
724
725 data CoreToDo           -- These are diff core-to-core passes,
726                         -- which may be invoked in any order,
727                         -- as many times as you like.
728
729   = CoreDoSimplify      -- The core-to-core simplifier.
730         SimplifierMode
731         [SimplifierSwitch]
732                         -- Each run of the simplifier can take a different
733                         -- set of simplifier-specific flags.
734   | CoreDoFloatInwards
735   | CoreDoFloatOutwards FloatOutSwitches
736   | CoreLiberateCase
737   | CoreDoPrintCore
738   | CoreDoStaticArgs
739   | CoreDoStrictness
740   | CoreDoWorkerWrapper
741   | CoreDoSpecialising
742   | CoreDoSpecConstr
743   | CoreDoOldStrictness
744   | CoreDoGlomBinds
745   | CoreCSE
746   | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules 
747                                                 -- matching this string
748   | CoreDoVectorisation
749   | CoreDoNothing                -- Useful when building up 
750   | CoreDoPasses [CoreToDo]      -- lists of these things
751
752 data SimplifierMode             -- See comments in SimplMonad
753   = SimplGently
754   | SimplPhase Int
755
756 data SimplifierSwitch
757   = MaxSimplifierIterations Int
758   | NoCaseOfCase
759
760 data FloatOutSwitches
761   = FloatOutSw  Bool    -- True <=> float lambdas to top level
762                 Bool    -- True <=> float constants to top level,
763                         --          even if they do not escape a lambda
764
765
766 -- The core-to-core pass ordering is derived from the DynFlags:
767 runWhen :: Bool -> CoreToDo -> CoreToDo
768 runWhen True  do_this = do_this
769 runWhen False do_this = CoreDoNothing
770
771 getCoreToDo :: DynFlags -> [CoreToDo]
772 getCoreToDo dflags
773   | Just todo <- coreToDo dflags = todo -- set explicitly by user
774   | otherwise = core_todo
775   where
776     opt_level     = optLevel dflags
777     max_iter      = maxSimplIterations dflags
778     strictness    = dopt Opt_Strictness dflags
779     full_laziness = dopt Opt_FullLaziness dflags
780     cse           = dopt Opt_CSE dflags
781     spec_constr   = dopt Opt_SpecConstr dflags
782     liberate_case = dopt Opt_LiberateCase dflags
783     rule_check    = ruleCheck dflags
784     vectorisation = dopt Opt_Vectorise dflags
785
786     core_todo = 
787      if opt_level == 0 then
788       [
789         CoreDoSimplify (SimplPhase 0) [
790             MaxSimplifierIterations max_iter
791         ]
792       ]
793      else {- opt_level >= 1 -} [ 
794
795         -- initial simplify: mk specialiser happy: minimum effort please
796         CoreDoSimplify SimplGently [
797                         --      Simplify "gently"
798                         -- Don't inline anything till full laziness has bitten
799                         -- In particular, inlining wrappers inhibits floating
800                         -- e.g. ...(case f x of ...)...
801                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
802                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
803                         -- and now the redex (f x) isn't floatable any more
804                         -- Similarly, don't apply any rules until after full 
805                         -- laziness.  Notably, list fusion can prevent floating.
806
807             NoCaseOfCase,       -- Don't do case-of-case transformations.
808                                 -- This makes full laziness work better
809             MaxSimplifierIterations max_iter
810         ],
811
812
813         -- We run vectorisation here for now, but we might also try to run
814         -- it later
815         runWhen vectorisation (CoreDoPasses [
816                   CoreDoVectorisation,
817                   CoreDoSimplify SimplGently
818                                   [NoCaseOfCase,
819                                    MaxSimplifierIterations max_iter]]),
820
821         -- Specialisation is best done before full laziness
822         -- so that overloaded functions have all their dictionary lambdas manifest
823         CoreDoSpecialising,
824
825         runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
826
827         CoreDoFloatInwards,
828
829         CoreDoSimplify (SimplPhase 2) [
830                 -- Want to run with inline phase 2 after the specialiser to give
831                 -- maximum chance for fusion to work before we inline build/augment
832                 -- in phase 1.  This made a difference in 'ansi' where an 
833                 -- overloaded function wasn't inlined till too late.
834            MaxSimplifierIterations max_iter
835         ],
836         case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
837
838         CoreDoSimplify (SimplPhase 1) [
839                 -- Need inline-phase2 here so that build/augment get 
840                 -- inlined.  I found that spectral/hartel/genfft lost some useful
841                 -- strictness in the function sumcode' if augment is not inlined
842                 -- before strictness analysis runs
843            MaxSimplifierIterations max_iter
844         ],
845         case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
846
847         CoreDoSimplify (SimplPhase 0) [
848                 -- Phase 0: allow all Ids to be inlined now
849                 -- This gets foldr inlined before strictness analysis
850
851            MaxSimplifierIterations 3
852                 -- At least 3 iterations because otherwise we land up with
853                 -- huge dead expressions because of an infelicity in the 
854                 -- simpifier.   
855                 --      let k = BIG in foldr k z xs
856                 -- ==>  let k = BIG in letrec go = \xs -> ...(k x).... in go xs
857                 -- ==>  let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
858                 -- Don't stop now!
859
860         ],
861         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
862
863 #ifdef OLD_STRICTNESS
864         CoreDoOldStrictness,
865 #endif
866         runWhen strictness (CoreDoPasses [
867                 CoreDoStrictness,
868                 CoreDoWorkerWrapper,
869                 CoreDoGlomBinds,
870                 CoreDoSimplify (SimplPhase 0) [
871                    MaxSimplifierIterations max_iter
872                 ]]),
873
874         runWhen full_laziness 
875           (CoreDoFloatOutwards (FloatOutSw False    -- Not lambdas
876                                            True)),  -- Float constants
877                 -- nofib/spectral/hartel/wang doubles in speed if you
878                 -- do full laziness late in the day.  It only happens
879                 -- after fusion and other stuff, so the early pass doesn't
880                 -- catch it.  For the record, the redex is 
881                 --        f_el22 (f_el21 r_midblock)
882
883
884         runWhen cse CoreCSE,
885                 -- We want CSE to follow the final full-laziness pass, because it may
886                 -- succeed in commoning up things floated out by full laziness.
887                 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
888
889         CoreDoFloatInwards,
890
891         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
892
893                 -- Case-liberation for -O2.  This should be after
894                 -- strictness analysis and the simplification which follows it.
895         runWhen liberate_case (CoreDoPasses [
896             CoreLiberateCase,
897             CoreDoSimplify (SimplPhase 0) [
898                   MaxSimplifierIterations max_iter
899             ] ]),       -- Run the simplifier after LiberateCase to vastly 
900                         -- reduce the possiblility of shadowing
901                         -- Reason: see Note [Shadowing] in SpecConstr.lhs
902
903         runWhen spec_constr CoreDoSpecConstr,
904
905         -- Final clean-up simplification:
906         CoreDoSimplify (SimplPhase 0) [
907           MaxSimplifierIterations max_iter
908         ]
909      ]
910
911 -- -----------------------------------------------------------------------------
912 -- StgToDo:  abstraction of stg-to-stg passes to run.
913
914 data StgToDo
915   = StgDoMassageForProfiling  -- should be (next to) last
916   -- There's also setStgVarInfo, but its absolute "lastness"
917   -- is so critical that it is hardwired in (no flag).
918   | D_stg_stats
919
920 getStgToDo :: DynFlags -> [StgToDo]
921 getStgToDo dflags
922   | Just todo <- stgToDo dflags = todo -- set explicitly by user
923   | otherwise = todo2
924   where
925         stg_stats = dopt Opt_StgStats dflags
926
927         todo1 = if stg_stats then [D_stg_stats] else []
928
929         todo2 | WayProf `elem` wayNames dflags
930               = StgDoMassageForProfiling : todo1
931               | otherwise
932               = todo1
933
934 -- -----------------------------------------------------------------------------
935 -- DynFlags parser
936
937 allFlags :: [String]
938 allFlags = map ('-':) $
939            [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
940            map ("fno-"++) flags ++
941            map ("f"++) flags
942     where ok (PrefixPred _ _) = False
943           ok _ = True
944           flags = map fst fFlags
945
946 dynamic_flags :: [(String, OptKind DynP)]
947 dynamic_flags = [
948      ( "n"              , NoArg  (setDynFlag Opt_DryRun) )
949   ,  ( "cpp"            , NoArg  (setDynFlag Opt_Cpp))
950   ,  ( "F"              , NoArg  (setDynFlag Opt_Pp))
951   ,  ( "#include"       , HasArg (addCmdlineHCInclude) )
952   ,  ( "v"              , OptIntSuffix setVerbosity )
953
954         ------- Specific phases  --------------------------------------------
955   ,  ( "pgmL"           , HasArg (upd . setPgmL) )  
956   ,  ( "pgmP"           , HasArg (upd . setPgmP) )  
957   ,  ( "pgmF"           , HasArg (upd . setPgmF) )  
958   ,  ( "pgmc"           , HasArg (upd . setPgmc) )  
959   ,  ( "pgmm"           , HasArg (upd . setPgmm) )  
960   ,  ( "pgms"           , HasArg (upd . setPgms) )  
961   ,  ( "pgma"           , HasArg (upd . setPgma) )  
962   ,  ( "pgml"           , HasArg (upd . setPgml) )  
963   ,  ( "pgmdll"         , HasArg (upd . setPgmdll) )
964   ,  ( "pgmwindres"     , HasArg (upd . setPgmwindres) )
965
966   ,  ( "optL"           , HasArg (upd . addOptL) )  
967   ,  ( "optP"           , HasArg (upd . addOptP) )  
968   ,  ( "optF"           , HasArg (upd . addOptF) )  
969   ,  ( "optc"           , HasArg (upd . addOptc) )  
970   ,  ( "optm"           , HasArg (upd . addOptm) )  
971   ,  ( "opta"           , HasArg (upd . addOpta) )  
972   ,  ( "optl"           , HasArg (upd . addOptl) )  
973   ,  ( "optdep"         , HasArg (upd . addOptdep) )
974   ,  ( "optwindres"     , HasArg (upd . addOptwindres) )
975
976   ,  ( "split-objs"     , NoArg (if can_split
977                                     then setDynFlag Opt_SplitObjs
978                                     else return ()) )
979
980         -------- Linking ----------------------------------------------------
981   ,  ( "c"              , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
982   ,  ( "no-link"        , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
983   ,  ( "shared"         , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
984
985         ------- Libraries ---------------------------------------------------
986   ,  ( "L"              , Prefix addLibraryPath )
987   ,  ( "l"              , AnySuffix (\s -> do upd (addOptl s)))
988
989         ------- Frameworks --------------------------------------------------
990         -- -framework-path should really be -F ...
991   ,  ( "framework-path" , HasArg addFrameworkPath )
992   ,  ( "framework"      , HasArg (upd . addCmdlineFramework) )
993
994         ------- Output Redirection ------------------------------------------
995   ,  ( "odir"           , HasArg (upd . setObjectDir))
996   ,  ( "o"              , SepArg (upd . setOutputFile . Just))
997   ,  ( "ohi"            , HasArg (upd . setOutputHi   . Just ))
998   ,  ( "osuf"           , HasArg (upd . setObjectSuf))
999   ,  ( "hcsuf"          , HasArg (upd . setHcSuf))
1000   ,  ( "hisuf"          , HasArg (upd . setHiSuf))
1001   ,  ( "hidir"          , HasArg (upd . setHiDir))
1002   ,  ( "tmpdir"         , HasArg (upd . setTmpDir))
1003   ,  ( "stubdir"        , HasArg (upd . setStubDir))
1004   ,  ( "ddump-file-prefix", HasArg (upd . setDumpPrefixForce . Just))
1005
1006         ------- Keeping temporary files -------------------------------------
1007      -- These can be singular (think ghc -c) or plural (think ghc --make)
1008   ,  ( "keep-hc-file"    , NoArg (setDynFlag Opt_KeepHcFiles))
1009   ,  ( "keep-hc-files"   , NoArg (setDynFlag Opt_KeepHcFiles))
1010   ,  ( "keep-s-file"     , NoArg (setDynFlag Opt_KeepSFiles))
1011   ,  ( "keep-s-files"    , NoArg (setDynFlag Opt_KeepSFiles))
1012   ,  ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
1013   ,  ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
1014      -- This only makes sense as plural
1015   ,  ( "keep-tmp-files"  , NoArg (setDynFlag Opt_KeepTmpFiles))
1016
1017         ------- Miscellaneous ----------------------------------------------
1018   ,  ( "no-hs-main"     , NoArg (setDynFlag Opt_NoHsMain))
1019   ,  ( "main-is"        , SepArg setMainIs )
1020   ,  ( "haddock"        , NoArg (setDynFlag Opt_Haddock) )
1021   ,  ( "haddock-opts"   , HasArg (upd . addHaddockOpts))
1022   ,  ( "hpcdir"         , SepArg setOptHpcDir )
1023
1024         ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
1025   ,  ( "recomp"         , NoArg (unSetDynFlag Opt_ForceRecomp) )
1026   ,  ( "no-recomp"      , NoArg (setDynFlag   Opt_ForceRecomp) )
1027
1028         ------- Packages ----------------------------------------------------
1029   ,  ( "package-conf"   , HasArg extraPkgConf_ )
1030   ,  ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
1031   ,  ( "package-name"   , HasArg (upd . setPackageName) )
1032   ,  ( "package"        , HasArg exposePackage )
1033   ,  ( "hide-package"   , HasArg hidePackage )
1034   ,  ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
1035   ,  ( "ignore-package" , HasArg ignorePackage )
1036   ,  ( "syslib"         , HasArg exposePackage )  -- for compatibility
1037
1038         ------ HsCpp opts ---------------------------------------------------
1039   ,  ( "D",             AnySuffix (upd . addOptP) )
1040   ,  ( "U",             AnySuffix (upd . addOptP) )
1041
1042         ------- Include/Import Paths ----------------------------------------
1043   ,  ( "I"              , Prefix    addIncludePath)
1044   ,  ( "i"              , OptPrefix addImportPath )
1045
1046         ------ Debugging ----------------------------------------------------
1047   ,  ( "dstg-stats",    NoArg (setDynFlag Opt_StgStats))
1048
1049   ,  ( "ddump-cmm",              setDumpFlag Opt_D_dump_cmm)
1050   ,  ( "ddump-cmmz",             setDumpFlag Opt_D_dump_cmmz)
1051   ,  ( "ddump-cmmz-pretty",      setDumpFlag Opt_D_dump_cmmz_pretty)
1052   ,  ( "ddump-cps-cmm",          setDumpFlag Opt_D_dump_cps_cmm)
1053   ,  ( "ddump-cvt-cmm",          setDumpFlag Opt_D_dump_cvt_cmm)
1054   ,  ( "ddump-asm",              setDumpFlag Opt_D_dump_asm)
1055   ,  ( "ddump-asm-native",       setDumpFlag Opt_D_dump_asm_native)
1056   ,  ( "ddump-asm-liveness",     setDumpFlag Opt_D_dump_asm_liveness)
1057   ,  ( "ddump-asm-coalesce",     setDumpFlag Opt_D_dump_asm_coalesce)
1058   ,  ( "ddump-asm-regalloc",     setDumpFlag Opt_D_dump_asm_regalloc)
1059   ,  ( "ddump-asm-conflicts",    setDumpFlag Opt_D_dump_asm_conflicts)
1060   ,  ( "ddump-asm-regalloc-stages",
1061                                  setDumpFlag Opt_D_dump_asm_regalloc_stages)
1062   ,  ( "ddump-asm-stats",        setDumpFlag Opt_D_dump_asm_stats)
1063   ,  ( "ddump-cpranal",          setDumpFlag Opt_D_dump_cpranal)
1064   ,  ( "ddump-deriv",            setDumpFlag Opt_D_dump_deriv)
1065   ,  ( "ddump-ds",               setDumpFlag Opt_D_dump_ds)
1066   ,  ( "ddump-flatC",            setDumpFlag Opt_D_dump_flatC)
1067   ,  ( "ddump-foreign",          setDumpFlag Opt_D_dump_foreign)
1068   ,  ( "ddump-inlinings",        setDumpFlag Opt_D_dump_inlinings)
1069   ,  ( "ddump-rule-firings",     setDumpFlag Opt_D_dump_rule_firings)
1070   ,  ( "ddump-occur-anal",       setDumpFlag Opt_D_dump_occur_anal)
1071   ,  ( "ddump-parsed",           setDumpFlag Opt_D_dump_parsed)
1072   ,  ( "ddump-rn",               setDumpFlag Opt_D_dump_rn)
1073   ,  ( "ddump-simpl",            setDumpFlag Opt_D_dump_simpl)
1074   ,  ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
1075   ,  ( "ddump-spec",             setDumpFlag Opt_D_dump_spec)
1076   ,  ( "ddump-prep",             setDumpFlag Opt_D_dump_prep)
1077   ,  ( "ddump-stg",              setDumpFlag Opt_D_dump_stg)
1078   ,  ( "ddump-stranal",          setDumpFlag Opt_D_dump_stranal)
1079   ,  ( "ddump-tc",               setDumpFlag Opt_D_dump_tc)
1080   ,  ( "ddump-types",            setDumpFlag Opt_D_dump_types)
1081   ,  ( "ddump-rules",            setDumpFlag Opt_D_dump_rules)
1082   ,  ( "ddump-cse",              setDumpFlag Opt_D_dump_cse)
1083   ,  ( "ddump-worker-wrapper",   setDumpFlag Opt_D_dump_worker_wrapper)
1084   ,  ( "ddump-rn-trace",         setDumpFlag Opt_D_dump_rn_trace)
1085   ,  ( "ddump-if-trace",         setDumpFlag Opt_D_dump_if_trace)
1086   ,  ( "ddump-tc-trace",         setDumpFlag Opt_D_dump_tc_trace)
1087   ,  ( "ddump-splices",          setDumpFlag Opt_D_dump_splices)
1088   ,  ( "ddump-rn-stats",         setDumpFlag Opt_D_dump_rn_stats)
1089   ,  ( "ddump-opt-cmm",          setDumpFlag Opt_D_dump_opt_cmm)
1090   ,  ( "ddump-simpl-stats",      setDumpFlag Opt_D_dump_simpl_stats)
1091   ,  ( "ddump-bcos",             setDumpFlag Opt_D_dump_BCOs)
1092   ,  ( "dsource-stats",          setDumpFlag Opt_D_source_stats)
1093   ,  ( "dverbose-core2core",     setDumpFlag Opt_D_verbose_core2core)
1094   ,  ( "dverbose-stg2stg",       setDumpFlag Opt_D_verbose_stg2stg)
1095   ,  ( "ddump-hi",               setDumpFlag Opt_D_dump_hi)
1096   ,  ( "ddump-minimal-imports",  setDumpFlag Opt_D_dump_minimal_imports)
1097   ,  ( "ddump-vect",             setDumpFlag Opt_D_dump_vect)
1098   ,  ( "ddump-hpc",              setDumpFlag Opt_D_dump_hpc)
1099   ,  ( "ddump-mod-cycles",       setDumpFlag Opt_D_dump_mod_cycles)
1100   ,  ( "ddump-view-pattern-commoning", setDumpFlag Opt_D_dump_view_pattern_commoning)
1101   ,  ( "ddump-to-file",          setDumpFlag Opt_DumpToFile)
1102   ,  ( "ddump-hi-diffs",         NoArg (setDynFlag Opt_D_dump_hi_diffs))
1103   ,  ( "dcore-lint",             NoArg (setDynFlag Opt_DoCoreLinting))
1104   ,  ( "dstg-lint",              NoArg (setDynFlag Opt_DoStgLinting))
1105   ,  ( "dcmm-lint",              NoArg (setDynFlag Opt_DoCmmLinting))
1106   ,  ( "dasm-lint",              NoArg (setDynFlag Opt_DoAsmLinting))
1107   ,  ( "dshow-passes",           NoArg (do setDynFlag Opt_ForceRecomp
1108                                            setVerbosity (Just 2)) )
1109   ,  ( "dfaststring-stats",      NoArg (setDynFlag Opt_D_faststring_stats))
1110
1111         ------ Machine dependant (-m<blah>) stuff ---------------------------
1112
1113   ,  ( "monly-2-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1114   ,  ( "monly-3-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1115   ,  ( "monly-4-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1116
1117      ------ Warning opts -------------------------------------------------
1118   ,  ( "W"     , NoArg (mapM_ setDynFlag   minusWOpts)    )
1119   ,  ( "Werror", NoArg (setDynFlag         Opt_WarnIsError) )
1120   ,  ( "Wwarn" , NoArg (unSetDynFlag       Opt_WarnIsError) )
1121   ,  ( "Wall"  , NoArg (mapM_ setDynFlag   minusWallOpts) )
1122   ,  ( "Wnot"  , NoArg (mapM_ unSetDynFlag minusWallOpts) ) -- DEPRECATED
1123   ,  ( "w"     , NoArg (mapM_ unSetDynFlag minuswRemovesOpts) )
1124
1125         ------ Optimisation flags ------------------------------------------
1126   ,  ( "O"      , NoArg (upd (setOptLevel 1)))
1127   ,  ( "Onot"   , NoArg (upd (setOptLevel 0))) -- deprecated
1128   ,  ( "O"      , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1129                 -- If the number is missing, use 1
1130
1131   ,  ( "fmax-simplifier-iterations", IntSuffix (\n -> 
1132                 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1133
1134         -- liberate-case-threshold is an old flag for '-fspec-threshold'
1135   ,  ( "fspec-threshold",          IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1136   ,  ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1137
1138   ,  ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1139   ,  ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1140
1141         ------ Compiler flags -----------------------------------------------
1142
1143   ,  ( "fasm",             NoArg (setObjTarget HscAsm) )
1144   ,  ( "fvia-c",           NoArg (setObjTarget HscC) )
1145   ,  ( "fvia-C",           NoArg (setObjTarget HscC) )
1146
1147   ,  ( "fno-code",         NoArg (setTarget HscNothing))
1148   ,  ( "fbyte-code",       NoArg (setTarget HscInterpreted) )
1149   ,  ( "fobject-code",     NoArg (setTarget defaultHscTarget) )
1150
1151   ,  ( "fglasgow-exts",    NoArg (mapM_ setDynFlag   glasgowExtsFlags) )
1152   ,  ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1153
1154      -- the rest of the -f* and -fno-* flags
1155   ,  ( "f",                PrefixPred (isFlag   fFlags)
1156                            (\f -> setDynFlag   (getFlag   fFlags f)) )
1157   ,  ( "f",                PrefixPred (isPrefFlag "no-" fFlags)
1158                            (\f -> unSetDynFlag (getPrefFlag "no-" fFlags f)) )
1159
1160      -- the -X* and -XNo* flags
1161   ,  ( "X",                PrefixPred (isFlag   xFlags)
1162                            (\f -> setDynFlag   (getFlag   xFlags f)) )
1163   ,  ( "X",                PrefixPred (isPrefFlag "No" xFlags)
1164                            (\f -> unSetDynFlag (getPrefFlag "No" xFlags f)) )
1165  ]
1166
1167 -- these -f<blah> flags can all be reversed with -fno-<blah>
1168
1169 fFlags = [
1170   ( "warn-dodgy-imports",               Opt_WarnDodgyImports ),
1171   ( "warn-duplicate-exports",           Opt_WarnDuplicateExports ),
1172   ( "warn-hi-shadowing",                Opt_WarnHiShadows ),
1173   ( "warn-implicit-prelude",            Opt_WarnImplicitPrelude ),
1174   ( "warn-incomplete-patterns",         Opt_WarnIncompletePatterns ),
1175   ( "warn-incomplete-record-updates",   Opt_WarnIncompletePatternsRecUpd ),
1176   ( "warn-missing-fields",              Opt_WarnMissingFields ),
1177   ( "warn-missing-methods",             Opt_WarnMissingMethods ),
1178   ( "warn-missing-signatures",          Opt_WarnMissingSigs ),
1179   ( "warn-name-shadowing",              Opt_WarnNameShadowing ),
1180   ( "warn-overlapping-patterns",        Opt_WarnOverlappingPatterns ),
1181   ( "warn-simple-patterns",             Opt_WarnSimplePatterns ),
1182   ( "warn-type-defaults",               Opt_WarnTypeDefaults ),
1183   ( "warn-monomorphism-restriction",    Opt_WarnMonomorphism ),
1184   ( "warn-unused-binds",                Opt_WarnUnusedBinds ),
1185   ( "warn-unused-imports",              Opt_WarnUnusedImports ),
1186   ( "warn-unused-matches",              Opt_WarnUnusedMatches ),
1187   ( "warn-deprecations",                Opt_WarnDeprecations ),
1188   ( "warn-orphans",                     Opt_WarnOrphans ),
1189   ( "warn-tabs",                        Opt_WarnTabs ),
1190   ( "print-explicit-foralls",           Opt_PrintExplicitForalls ),
1191   ( "strictness",                       Opt_Strictness ),
1192   ( "full-laziness",                    Opt_FullLaziness ),
1193   ( "liberate-case",                    Opt_LiberateCase ),
1194   ( "spec-constr",                      Opt_SpecConstr ),
1195   ( "cse",                              Opt_CSE ),
1196   ( "ignore-interface-pragmas",         Opt_IgnoreInterfacePragmas ),
1197   ( "omit-interface-pragmas",           Opt_OmitInterfacePragmas ),
1198   ( "do-lambda-eta-expansion",          Opt_DoLambdaEtaExpansion ),
1199   ( "ignore-asserts",                   Opt_IgnoreAsserts ),
1200   ( "ignore-breakpoints",               Opt_IgnoreBreakpoints),
1201   ( "do-eta-reduction",                 Opt_DoEtaReduction ),
1202   ( "case-merge",                       Opt_CaseMerge ),
1203   ( "unbox-strict-fields",              Opt_UnboxStrictFields ),
1204   ( "dicts-cheap",                      Opt_DictsCheap ),
1205   ( "excess-precision",                 Opt_ExcessPrecision ),
1206   ( "asm-mangling",                     Opt_DoAsmMangling ),
1207   ( "print-bind-result",                Opt_PrintBindResult ),
1208   ( "force-recomp",                     Opt_ForceRecomp ),
1209   ( "hpc-no-auto",                      Opt_Hpc_No_Auto ),
1210   ( "rewrite-rules",                    Opt_RewriteRules ),
1211   ( "break-on-exception",               Opt_BreakOnException ),
1212   ( "break-on-error",                   Opt_BreakOnError ),
1213   ( "print-evld-with-show",             Opt_PrintEvldWithShow ),
1214   ( "run-cps",                          Opt_RunCPSZ ),
1215   ( "convert-to-zipper-and-back",       Opt_ConvertToZipCfgAndBack),
1216   ( "vectorise",                        Opt_Vectorise ),
1217   ( "regs-graph",                       Opt_RegsGraph),
1218   ( "regs-iterative",                   Opt_RegsIterative),
1219   -- Deprecated in favour of -XTemplateHaskell:
1220   ( "th",                               Opt_TemplateHaskell ),
1221   -- Deprecated in favour of -XForeignFunctionInterface:
1222   ( "fi",                               Opt_ForeignFunctionInterface ),
1223   -- Deprecated in favour of -XForeignFunctionInterface:
1224   ( "ffi",                              Opt_ForeignFunctionInterface ),
1225   -- Deprecated in favour of -XArrows:
1226   ( "arrows",                           Opt_Arrows ),
1227   -- Deprecated in favour of -XGenerics:
1228   ( "generics",                         Opt_Generics ),
1229   -- Deprecated in favour of -XImplicitPrelude:
1230   ( "implicit-prelude",                 Opt_ImplicitPrelude ),
1231   -- Deprecated in favour of -XBangPatterns:
1232   ( "bang-patterns",                    Opt_BangPatterns ),
1233   -- Deprecated in favour of -XMonomorphismRestriction:
1234   ( "monomorphism-restriction",         Opt_MonomorphismRestriction ),
1235   -- Deprecated in favour of -XMonoPatBinds:
1236   ( "mono-pat-binds",                   Opt_MonoPatBinds ),
1237   -- Deprecated in favour of -XExtendedDefaultRules:
1238   ( "extended-default-rules",           Opt_ExtendedDefaultRules ),
1239   -- Deprecated in favour of -XImplicitParams:
1240   ( "implicit-params",                  Opt_ImplicitParams ),
1241   -- Deprecated in favour of -XScopedTypeVariables:
1242   ( "scoped-type-variables",            Opt_ScopedTypeVariables ),
1243   -- Deprecated in favour of -XPArr:
1244   ( "parr",                             Opt_PArr ),
1245   -- Deprecated in favour of -XOverlappingInstances:
1246   ( "allow-overlapping-instances",      Opt_OverlappingInstances ),
1247   -- Deprecated in favour of -XUndecidableInstances:
1248   ( "allow-undecidable-instances",      Opt_UndecidableInstances ),
1249   -- Deprecated in favour of -XIncoherentInstances:
1250   ( "allow-incoherent-instances",       Opt_IncoherentInstances ),
1251   ( "gen-manifest",                     Opt_GenManifest ),
1252   ( "embed-manifest",                   Opt_EmbedManifest )
1253   ]
1254
1255 supportedLanguages :: [String]
1256 supportedLanguages = map fst xFlags
1257
1258 -- These -X<blah> flags can all be reversed with -XNo<blah>
1259 xFlags :: [(String, DynFlag)]
1260 xFlags = [
1261   ( "CPP",                              Opt_Cpp ),
1262   ( "PatternGuards",                    Opt_PatternGuards ),
1263   ( "UnicodeSyntax",                    Opt_UnicodeSyntax ),
1264   ( "MagicHash",                        Opt_MagicHash ),
1265   ( "PolymorphicComponents",            Opt_PolymorphicComponents ),
1266   ( "ExistentialQuantification",        Opt_ExistentialQuantification ),
1267   ( "KindSignatures",                   Opt_KindSignatures ),
1268   ( "PatternSignatures",                Opt_PatternSignatures ),
1269   ( "EmptyDataDecls",                   Opt_EmptyDataDecls ),
1270   ( "ParallelListComp",                 Opt_ParallelListComp ),
1271   ( "ForeignFunctionInterface",         Opt_ForeignFunctionInterface ),
1272   ( "UnliftedFFITypes",                 Opt_UnliftedFFITypes ),
1273   ( "LiberalTypeSynonyms",              Opt_LiberalTypeSynonyms ),
1274   ( "Rank2Types",                       Opt_Rank2Types ),
1275   ( "RankNTypes",                       Opt_RankNTypes ),
1276   ( "TypeOperators",                    Opt_TypeOperators ),
1277   ( "RecursiveDo",                      Opt_RecursiveDo ),
1278   ( "Arrows",                           Opt_Arrows ),
1279   ( "PArr",                             Opt_PArr ),
1280   ( "TemplateHaskell",                  Opt_TemplateHaskell ),
1281   ( "Generics",                         Opt_Generics ),
1282   -- On by default:
1283   ( "ImplicitPrelude",                  Opt_ImplicitPrelude ),
1284   ( "RecordWildCards",                  Opt_RecordWildCards ),
1285   ( "RecordPuns",                       Opt_RecordPuns ),
1286   ( "DisambiguateRecordFields",         Opt_DisambiguateRecordFields ),
1287   ( "OverloadedStrings",                Opt_OverloadedStrings ),
1288   ( "GADTs",                            Opt_GADTs ),
1289   ( "ViewPatterns",                     Opt_ViewPatterns),
1290   ( "TypeFamilies",                     Opt_TypeFamilies ),
1291   ( "BangPatterns",                     Opt_BangPatterns ),
1292   -- On by default:
1293   ( "MonomorphismRestriction",          Opt_MonomorphismRestriction ),
1294   -- On by default (which is not strictly H98):
1295   ( "MonoPatBinds",                     Opt_MonoPatBinds ),
1296   ( "RelaxedPolyRec",                   Opt_RelaxedPolyRec),
1297   ( "ExtendedDefaultRules",             Opt_ExtendedDefaultRules ),
1298   ( "ImplicitParams",                   Opt_ImplicitParams ),
1299   ( "ScopedTypeVariables",              Opt_ScopedTypeVariables ),
1300   ( "UnboxedTuples",                    Opt_UnboxedTuples ),
1301   ( "StandaloneDeriving",               Opt_StandaloneDeriving ),
1302   ( "DeriveDataTypeable",               Opt_DeriveDataTypeable ),
1303   ( "TypeSynonymInstances",             Opt_TypeSynonymInstances ),
1304   ( "FlexibleContexts",                 Opt_FlexibleContexts ),
1305   ( "FlexibleInstances",                Opt_FlexibleInstances ),
1306   ( "ConstrainedClassMethods",          Opt_ConstrainedClassMethods ),
1307   ( "MultiParamTypeClasses",            Opt_MultiParamTypeClasses ),
1308   ( "FunctionalDependencies",           Opt_FunctionalDependencies ),
1309   ( "GeneralizedNewtypeDeriving",       Opt_GeneralizedNewtypeDeriving ),
1310   ( "OverlappingInstances",             Opt_OverlappingInstances ),
1311   ( "UndecidableInstances",             Opt_UndecidableInstances ),
1312   ( "IncoherentInstances",              Opt_IncoherentInstances )
1313   ]
1314
1315 impliedFlags :: [(DynFlag, [DynFlag])]
1316 impliedFlags = [
1317   ( Opt_GADTs, [Opt_RelaxedPolyRec] )   -- We want type-sig variables to be completely rigid for GADTs
1318   ]
1319
1320 glasgowExtsFlags = [
1321              Opt_PrintExplicitForalls
1322            , Opt_ForeignFunctionInterface
1323            , Opt_UnliftedFFITypes
1324                    , Opt_GADTs
1325                    , Opt_ImplicitParams 
1326                    , Opt_ScopedTypeVariables
1327            , Opt_UnboxedTuples
1328            , Opt_TypeSynonymInstances
1329            , Opt_StandaloneDeriving
1330            , Opt_DeriveDataTypeable
1331            , Opt_FlexibleContexts
1332            , Opt_FlexibleInstances
1333            , Opt_ConstrainedClassMethods
1334            , Opt_MultiParamTypeClasses
1335            , Opt_FunctionalDependencies
1336                    , Opt_MagicHash
1337            , Opt_PolymorphicComponents
1338            , Opt_ExistentialQuantification
1339            , Opt_UnicodeSyntax
1340            , Opt_PatternGuards
1341            , Opt_LiberalTypeSynonyms
1342            , Opt_RankNTypes
1343            , Opt_TypeOperators
1344            , Opt_RecursiveDo
1345            , Opt_ParallelListComp
1346            , Opt_EmptyDataDecls
1347            , Opt_KindSignatures
1348            , Opt_PatternSignatures
1349            , Opt_GeneralizedNewtypeDeriving
1350                    , Opt_TypeFamilies ]
1351
1352 ------------------
1353 isFlag :: [(String,a)] -> String -> Bool
1354 isFlag flags f = any (\(ff,_) -> ff == f) flags
1355
1356 isPrefFlag :: String -> [(String,a)] -> String -> Bool
1357 isPrefFlag pref flags no_f
1358   | Just f <- maybePrefixMatch pref no_f = isFlag flags f
1359   | otherwise                            = False
1360
1361 ------------------
1362 getFlag :: [(String,a)] -> String -> a
1363 getFlag flags f = case [ opt | (ff, opt) <- flags, ff == f] of
1364                       (o:os) -> o
1365                       []     -> panic ("get_flag " ++ f)
1366
1367 getPrefFlag :: String -> [(String,a)] -> String -> a
1368 getPrefFlag pref flags f = getFlag flags (fromJust (maybePrefixMatch pref f))
1369 -- We should only be passed flags which match the prefix
1370
1371 -- -----------------------------------------------------------------------------
1372 -- Parsing the dynamic flags.
1373
1374 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1375 parseDynamicFlags dflags args = do
1376   let ((leftover,errs),dflags') 
1377           = runCmdLine (processArgs dynamic_flags args) dflags
1378   when (not (null errs)) $ do
1379     throwDyn (UsageError (unlines errs))
1380   return (dflags', leftover)
1381
1382
1383 type DynP = CmdLineP DynFlags
1384
1385 upd :: (DynFlags -> DynFlags) -> DynP ()
1386 upd f = do 
1387    dfs <- getCmdLineState
1388    putCmdLineState $! (f dfs)
1389
1390 --------------------------
1391 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1392 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1393   where
1394     deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1395         -- When you set f, set the ones it implies
1396         -- When you un-set f, however, we don't un-set the things it implies
1397         --      (except for -fno-glasgow-exts, which is treated specially)
1398
1399 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1400
1401 --------------------------
1402 setDumpFlag :: DynFlag -> OptKind DynP
1403 setDumpFlag dump_flag 
1404   = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1405         -- Whenver we -ddump, switch off the recompilation checker,
1406         -- else you don't see the dump!
1407
1408 setVerbosity :: Maybe Int -> DynP ()
1409 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1410
1411 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes =  a : cmdlineHcIncludes s})
1412
1413 extraPkgConf_  p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1414
1415 exposePackage p = 
1416   upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1417 hidePackage p = 
1418   upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1419 ignorePackage p = 
1420   upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1421
1422 setPackageName p
1423   | Nothing <- unpackPackageId pid
1424   = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1425   | otherwise
1426   = \s -> s{ thisPackage = pid }
1427   where
1428         pid = stringToPackageId p
1429
1430 -- If we're linking a binary, then only targets that produce object
1431 -- code are allowed (requests for other target types are ignored).
1432 setTarget l = upd set
1433   where 
1434    set dfs 
1435      | ghcLink dfs /= LinkBinary || isObjectTarget l  = dfs{ hscTarget = l }
1436      | otherwise = dfs
1437
1438 -- Changes the target only if we're compiling object code.  This is
1439 -- used by -fasm and -fvia-C, which switch from one to the other, but
1440 -- not from bytecode to object-code.  The idea is that -fasm/-fvia-C
1441 -- can be safely used in an OPTIONS_GHC pragma.
1442 setObjTarget l = upd set
1443   where 
1444    set dfs 
1445      | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1446      | otherwise = dfs
1447
1448 setOptLevel :: Int -> DynFlags -> DynFlags
1449 setOptLevel n dflags
1450    | hscTarget dflags == HscInterpreted && n > 0
1451         = dflags
1452             -- not in IO any more, oh well:
1453             -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1454    | otherwise
1455         = updOptLevel n dflags
1456
1457
1458 setMainIs :: String -> DynP ()
1459 setMainIs arg
1460   | not (null main_fn) && isLower (head main_fn)
1461      -- The arg looked like "Foo.Bar.baz"
1462   = upd $ \d -> d{ mainFunIs = Just main_fn,
1463                    mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1464
1465   | isUpper (head arg)  -- The arg looked like "Foo" or "Foo.Bar"
1466   = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
1467   
1468   | otherwise                   -- The arg looked like "baz"
1469   = upd $ \d -> d{ mainFunIs = Just arg }
1470   where
1471     (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1472
1473 -----------------------------------------------------------------------------
1474 -- Paths & Libraries
1475
1476 -- -i on its own deletes the import paths
1477 addImportPath "" = upd (\s -> s{importPaths = []})
1478 addImportPath p  = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1479
1480
1481 addLibraryPath p = 
1482   upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1483
1484 addIncludePath p = 
1485   upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1486
1487 addFrameworkPath p = 
1488   upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1489
1490 split_marker = ':'   -- not configurable (ToDo)
1491
1492 splitPathList :: String -> [String]
1493 splitPathList s = filter notNull (splitUp s)
1494                 -- empty paths are ignored: there might be a trailing
1495                 -- ':' in the initial list, for example.  Empty paths can
1496                 -- cause confusion when they are translated into -I options
1497                 -- for passing to gcc.
1498   where
1499 #ifndef mingw32_TARGET_OS
1500     splitUp xs = split split_marker xs
1501 #else 
1502      -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1503      -- 
1504      -- That is, if "foo:bar:baz" is used, this interpreted as
1505      -- consisting of three entries, 'foo', 'bar', 'baz'.
1506      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1507      -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1508      --
1509      -- Notice that no attempt is made to fully replace the 'standard'
1510      -- split marker ':' with the Windows / DOS one, ';'. The reason being
1511      -- that this will cause too much breakage for users & ':' will
1512      -- work fine even with DOS paths, if you're not insisting on being silly.
1513      -- So, use either.
1514     splitUp []             = []
1515     splitUp (x:':':div:xs) | div `elem` dir_markers
1516                            = ((x:':':div:p): splitUp rs)
1517                            where
1518                               (p,rs) = findNextPath xs
1519           -- we used to check for existence of the path here, but that
1520           -- required the IO monad to be threaded through the command-line
1521           -- parser which is quite inconvenient.  The 
1522     splitUp xs = cons p (splitUp rs)
1523                where
1524                  (p,rs) = findNextPath xs
1525     
1526                  cons "" xs = xs
1527                  cons x  xs = x:xs
1528
1529     -- will be called either when we've consumed nought or the
1530     -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1531     -- finding the next split marker.
1532     findNextPath xs = 
1533         case break (`elem` split_markers) xs of
1534            (p, d:ds) -> (p, ds)
1535            (p, xs)   -> (p, xs)
1536
1537     split_markers :: [Char]
1538     split_markers = [':', ';']
1539
1540     dir_markers :: [Char]
1541     dir_markers = ['/', '\\']
1542 #endif
1543
1544 -- -----------------------------------------------------------------------------
1545 -- tmpDir, where we store temporary files.
1546
1547 setTmpDir :: FilePath -> DynFlags -> DynFlags
1548 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1549   where
1550 #if !defined(mingw32_HOST_OS)
1551      canonicalise p = normalisePath p
1552 #else
1553         -- Canonicalisation of temp path under win32 is a bit more
1554         -- involved: (a) strip trailing slash, 
1555         --           (b) normalise slashes
1556         --           (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1557         -- 
1558      canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1559
1560         -- if we're operating under cygwin, and TMP/TEMP is of
1561         -- the form "/cygdrive/drive/path", translate this to
1562         -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1563         -- understand /cygdrive paths.)
1564      xltCygdrive path
1565       | "/cygdrive/" `isPrefixOf` path = 
1566           case drop (length "/cygdrive/") path of
1567             drive:xs@('/':_) -> drive:':':xs
1568             _ -> path
1569       | otherwise = path
1570
1571         -- strip the trailing backslash (awful, but we only do this once).
1572      removeTrailingSlash path = 
1573        case last path of
1574          '/'  -> init path
1575          '\\' -> init path
1576          _    -> path
1577 #endif
1578
1579 -----------------------------------------------------------------------------
1580 -- Hpc stuff
1581
1582 setOptHpcDir :: String -> DynP ()
1583 setOptHpcDir arg  = upd $ \ d -> d{hpcDir = arg}
1584
1585 -----------------------------------------------------------------------------
1586 -- Via-C compilation stuff
1587
1588 -- There are some options that we need to pass to gcc when compiling
1589 -- Haskell code via C, but are only supported by recent versions of
1590 -- gcc.  The configure script decides which of these options we need,
1591 -- and puts them in the file "extra-gcc-opts" in $topdir, which is
1592 -- read before each via-C compilation.  The advantage of having these
1593 -- in a separate file is that the file can be created at install-time
1594 -- depending on the available gcc version, and even re-generated  later
1595 -- if gcc is upgraded.
1596 --
1597 -- The options below are not dependent on the version of gcc, only the
1598 -- platform.
1599
1600 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1601                               [String]) -- for registerised HC compilations
1602 machdepCCOpts dflags
1603 #if alpha_TARGET_ARCH
1604         =       ( ["-w", "-mieee"
1605 #ifdef HAVE_THREADED_RTS_SUPPORT
1606                     , "-D_REENTRANT"
1607 #endif
1608                    ], [] )
1609         -- For now, to suppress the gcc warning "call-clobbered
1610         -- register used for global register variable", we simply
1611         -- disable all warnings altogether using the -w flag. Oh well.
1612
1613 #elif hppa_TARGET_ARCH
1614         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1615         -- (very nice, but too bad the HP /usr/include files don't agree.)
1616         = ( ["-D_HPUX_SOURCE"], [] )
1617
1618 #elif m68k_TARGET_ARCH
1619       -- -fno-defer-pop : for the .hc files, we want all the pushing/
1620       --    popping of args to routines to be explicit; if we let things
1621       --    be deferred 'til after an STGJUMP, imminent death is certain!
1622       --
1623       -- -fomit-frame-pointer : *don't*
1624       --     It's better to have a6 completely tied up being a frame pointer
1625       --     rather than let GCC pick random things to do with it.
1626       --     (If we want to steal a6, then we would try to do things
1627       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
1628         = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1629
1630 #elif i386_TARGET_ARCH
1631       -- -fno-defer-pop : basically the same game as for m68k
1632       --
1633       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1634       --   the fp (%ebp) for our register maps.
1635         =  let n_regs = stolen_x86_regs dflags
1636                sta = opt_Static
1637            in
1638                     ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1639 --                    , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else "" 
1640                       ],
1641                       [ "-fno-defer-pop",
1642                         "-fomit-frame-pointer",
1643                         -- we want -fno-builtin, because when gcc inlines
1644                         -- built-in functions like memcpy() it tends to
1645                         -- run out of registers, requiring -monly-n-regs
1646                         "-fno-builtin",
1647                         "-DSTOLEN_X86_REGS="++show n_regs ]
1648                     )
1649
1650 #elif ia64_TARGET_ARCH
1651         = ( [], ["-fomit-frame-pointer", "-G0"] )
1652
1653 #elif x86_64_TARGET_ARCH
1654         = ( [], ["-fomit-frame-pointer",
1655                  "-fno-asynchronous-unwind-tables",
1656                         -- the unwind tables are unnecessary for HC code,
1657                         -- and get in the way of -split-objs.  Another option
1658                         -- would be to throw them away in the mangler, but this
1659                         -- is easier.
1660                  "-fno-builtin"
1661                         -- calling builtins like strlen() using the FFI can
1662                         -- cause gcc to run out of regs, so use the external
1663                         -- version.
1664                 ] )
1665
1666 #elif sparc_TARGET_ARCH
1667         = ( [], ["-w"] )
1668         -- For now, to suppress the gcc warning "call-clobbered
1669         -- register used for global register variable", we simply
1670         -- disable all warnings altogether using the -w flag. Oh well.
1671
1672 #elif powerpc_apple_darwin_TARGET
1673       -- -no-cpp-precomp:
1674       --     Disable Apple's precompiling preprocessor. It's a great thing
1675       --     for "normal" programs, but it doesn't support register variable
1676       --     declarations.
1677         = ( [], ["-no-cpp-precomp"] )
1678 #else
1679         = ( [], [] )
1680 #endif
1681
1682 picCCOpts :: DynFlags -> [String]
1683 picCCOpts dflags
1684 #if darwin_TARGET_OS
1685       -- Apple prefers to do things the other way round.
1686       -- PIC is on by default.
1687       -- -mdynamic-no-pic:
1688       --     Turn off PIC code generation.
1689       -- -fno-common:
1690       --     Don't generate "common" symbols - these are unwanted
1691       --     in dynamic libraries.
1692
1693     | opt_PIC
1694         = ["-fno-common", "-D__PIC__"]
1695     | otherwise
1696         = ["-mdynamic-no-pic"]
1697 #elif mingw32_TARGET_OS
1698       -- no -fPIC for Windows
1699     | opt_PIC
1700         = ["-D__PIC__"]
1701     | otherwise
1702         = []
1703 #else
1704     | opt_PIC
1705         = ["-fPIC", "-D__PIC__"]
1706     | otherwise
1707         = []
1708 #endif
1709
1710 -- -----------------------------------------------------------------------------
1711 -- Splitting
1712
1713 can_split :: Bool
1714 can_split = cSplitObjs == "YES"
1715
1716 -- -----------------------------------------------------------------------------
1717 -- Compiler Info
1718
1719 compilerInfo :: [(String, String)]
1720 compilerInfo = [("Project name",                cProjectName),
1721                 ("Project version",             cProjectVersion),
1722                 ("Booter version",              cBooterVersion),
1723                 ("Stage",                       cStage),
1724                 ("Interface file version",      cHscIfaceFileVersion),
1725                 ("Have interpreter",            cGhcWithInterpreter),
1726                 ("Object splitting",            cSplitObjs),
1727                 ("Have native code generator",  cGhcWithNativeCodeGen),
1728                 ("Support SMP",                 cGhcWithSMP),
1729                 ("Unregisterised",              cGhcUnregisterised),
1730                 ("Tables next to code",         cGhcEnableTablesNextToCode),
1731                 ("Win32 DLLs",                  cEnableWin32DLLs),
1732                 ("RTS ways",                    cGhcRTSWays),
1733                 ("Leading underscore",          cLeadingUnderscore)]
1734