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