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