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