[project @ 2005-02-07 12:16:50 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / CmdLineOpts.lhs
1
2 % (c) The University of Glasgow, 1996-2000
3 %
4 \section[CmdLineOpts]{Things to do with command-line options}
5
6 \begin{code}
7
8 module CmdLineOpts (
9         CoreToDo(..), buildCoreToDo, StgToDo(..),
10         SimplifierSwitch(..), 
11         SimplifierMode(..), FloatOutSwitches(..),
12
13         HscTarget(..),
14         DynFlag(..),    -- needed non-abstractly by DriverFlags
15         DynFlags(..),
16         PackageFlag(..),
17
18         v_Static_hsc_opts,
19
20         isStaticHscFlag,
21
22         -- Manipulating DynFlags
23         defaultDynFlags,                -- DynFlags
24         dopt,                           -- DynFlag -> DynFlags -> Bool
25         dopt_set, dopt_unset,           -- DynFlags -> DynFlag -> DynFlags
26         dopt_CoreToDo,                  -- DynFlags -> [CoreToDo]
27         dopt_StgToDo,                   -- DynFlags -> [StgToDo]
28         dopt_HscTarget,                 -- DynFlags -> HscTarget
29         dopt_OutName,                   -- DynFlags -> String
30         getOpts,                        -- (DynFlags -> [a]) -> IO [a]
31         getVerbFlag,
32         updOptLevel,
33
34         -- sets of warning opts
35         minusWOpts,
36         minusWallOpts,
37
38         -- Output style options
39         opt_PprUserLength,
40         opt_PprStyle_Debug,
41
42         -- profiling opts
43         opt_AutoSccsOnAllToplevs,
44         opt_AutoSccsOnExportedToplevs,
45         opt_AutoSccsOnIndividualCafs,
46         opt_SccProfilingOn,
47         opt_DoTickyProfiling,
48
49         -- language opts
50         opt_DictsStrict,
51         opt_MaxContextReductionDepth,
52         opt_IrrefutableTuples,
53         opt_Parallel,
54         opt_SMP,
55         opt_RuntimeTypes,
56         opt_Flatten,
57
58         -- optimisation opts
59         opt_NoMethodSharing, 
60         opt_NoStateHack,
61         opt_LiberateCaseThreshold,
62         opt_CprOff,
63         opt_RulesOff,
64         opt_SimplNoPreInlining,
65         opt_SimplExcessPrecision,
66         opt_MaxWorkerArgs,
67
68         -- Unfolding control
69         opt_UF_CreationThreshold,
70         opt_UF_UseThreshold,
71         opt_UF_FunAppDiscount,
72         opt_UF_KeenessFactor,
73         opt_UF_UpdateInPlace,
74         opt_UF_DearOp,
75
76         -- misc opts
77         opt_ErrorSpans,
78         opt_EmitCExternDecls,
79         opt_EnsureSplittableC,
80         opt_GranMacros,
81         opt_HiVersion,
82         opt_HistorySize,
83         opt_OmitBlackHoling,
84         opt_Static,
85         opt_Unregisterised,
86         opt_EmitExternalCore,
87         opt_PIC
88     ) where
89
90 #include "HsVersions.h"
91
92 import {-# SOURCE #-} Packages (PackageState)
93 import DriverPhases     ( HscTarget(..) )
94 import Constants        -- Default values for some flags
95 import Util
96 import FastString       ( FastString, mkFastString )
97 import Config
98 import Maybes           ( firstJust )
99
100 import Panic            ( ghcError, GhcException(UsageError) )
101 import GLAEXTS
102 import DATA_IOREF       ( IORef, readIORef )
103 import UNSAFE_IO        ( unsafePerformIO )
104 \end{code}
105
106 %************************************************************************
107 %*                                                                      *
108 \subsection{Command-line options}
109 %*                                                                      *
110 %************************************************************************
111
112 The hsc command-line options are split into two categories:
113
114   - static flags
115   - dynamic flags
116
117 Static flags are represented by top-level values of type Bool or Int,
118 for example.  They therefore have the same value throughout the
119 invocation of hsc.
120
121 Dynamic flags are represented by an abstract type, DynFlags, which is
122 passed into hsc by the compilation manager for every compilation.
123 Dynamic flags are those that change on a per-compilation basis,
124 perhaps because they may be present in the OPTIONS pragma at the top
125 of a module.
126
127 Other flag-related blurb:
128
129 A list of {\em ToDo}s is things to be done in a particular part of
130 processing.  A (fictitious) example for the Core-to-Core simplifier
131 might be: run the simplifier, then run the strictness analyser, then
132 run the simplifier again (three ``todos'').
133
134 There are three ``to-do processing centers'' at the moment.  In the
135 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
136 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
137 (\tr{simplStg/SimplStg.lhs}).
138
139 %************************************************************************
140 %*                                                                      *
141 \subsection{Datatypes associated with command-line options}
142 %*                                                                      *
143 %************************************************************************
144
145 \begin{code}
146 data CoreToDo           -- These are diff core-to-core passes,
147                         -- which may be invoked in any order,
148                         -- as many times as you like.
149
150   = CoreDoSimplify      -- The core-to-core simplifier.
151         SimplifierMode
152         [SimplifierSwitch]
153                         -- Each run of the simplifier can take a different
154                         -- set of simplifier-specific flags.
155   | CoreDoFloatInwards
156   | CoreDoFloatOutwards FloatOutSwitches
157   | CoreLiberateCase
158   | CoreDoPrintCore
159   | CoreDoStaticArgs
160   | CoreDoStrictness
161   | CoreDoWorkerWrapper
162   | CoreDoSpecialising
163   | CoreDoSpecConstr
164   | CoreDoOldStrictness
165   | CoreDoGlomBinds
166   | CoreCSE
167   | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules 
168                                                 -- matching this string
169
170   | CoreDoNothing        -- useful when building up lists of these things
171 \end{code}
172
173 \begin{code}
174 data StgToDo
175   = StgDoMassageForProfiling  -- should be (next to) last
176   -- There's also setStgVarInfo, but its absolute "lastness"
177   -- is so critical that it is hardwired in (no flag).
178   | D_stg_stats
179 \end{code}
180
181 \begin{code}
182 data SimplifierMode             -- See comments in SimplMonad
183   = SimplGently
184   | SimplPhase Int
185
186 data SimplifierSwitch
187   = MaxSimplifierIterations Int
188   | NoCaseOfCase
189
190 data FloatOutSwitches
191   = FloatOutSw  Bool    -- True <=> float lambdas to top level
192                 Bool    -- True <=> float constants to top level,
193                         --          even if they do not escape a lambda
194 \end{code}
195
196 %************************************************************************
197 %*                                                                      *
198 \subsection{Dynamic command-line options}
199 %*                                                                      *
200 %************************************************************************
201
202 \begin{code}
203 data DynFlag
204
205    -- debugging flags
206    = Opt_D_dump_cmm
207    | Opt_D_dump_asm
208    | Opt_D_dump_cpranal
209    | Opt_D_dump_deriv
210    | Opt_D_dump_ds
211    | Opt_D_dump_flatC
212    | Opt_D_dump_foreign
213    | Opt_D_dump_inlinings
214    | Opt_D_dump_occur_anal
215    | Opt_D_dump_parsed
216    | Opt_D_dump_rn
217    | Opt_D_dump_simpl
218    | Opt_D_dump_simpl_iterations
219    | Opt_D_dump_spec
220    | Opt_D_dump_prep
221    | Opt_D_dump_stg
222    | Opt_D_dump_stranal
223    | Opt_D_dump_tc
224    | Opt_D_dump_types
225    | Opt_D_dump_rules
226    | Opt_D_dump_cse
227    | Opt_D_dump_worker_wrapper
228    | Opt_D_dump_rn_trace
229    | Opt_D_dump_rn_stats
230    | Opt_D_dump_opt_cmm
231    | Opt_D_dump_simpl_stats
232    | Opt_D_dump_tc_trace
233    | Opt_D_dump_if_trace
234    | Opt_D_dump_splices
235    | Opt_D_dump_BCOs
236    | Opt_D_dump_vect
237    | Opt_D_source_stats
238    | Opt_D_verbose_core2core
239    | Opt_D_verbose_stg2stg
240    | Opt_D_dump_hi
241    | Opt_D_dump_hi_diffs
242    | Opt_D_dump_minimal_imports
243    | Opt_DoCoreLinting
244    | Opt_DoStgLinting
245    | Opt_DoCmmLinting
246
247    | Opt_WarnIsError            -- -Werror; makes warnings fatal
248    | Opt_WarnDuplicateExports
249    | Opt_WarnHiShadows
250    | Opt_WarnIncompletePatterns
251    | Opt_WarnIncompletePatternsRecUpd
252    | Opt_WarnMissingFields
253    | Opt_WarnMissingMethods
254    | Opt_WarnMissingSigs
255    | Opt_WarnNameShadowing
256    | Opt_WarnOverlappingPatterns
257    | Opt_WarnSimplePatterns
258    | Opt_WarnTypeDefaults
259    | Opt_WarnUnusedBinds
260    | Opt_WarnUnusedImports
261    | Opt_WarnUnusedMatches
262    | Opt_WarnDeprecations
263    | Opt_WarnDodgyImports
264    | Opt_WarnOrphans
265
266    -- language opts
267    | Opt_AllowOverlappingInstances
268    | Opt_AllowUndecidableInstances
269    | Opt_AllowIncoherentInstances
270    | Opt_MonomorphismRestriction
271    | Opt_GlasgowExts
272    | Opt_FFI
273    | Opt_PArr                          -- syntactic support for parallel arrays
274    | Opt_Arrows                        -- Arrow-notation syntax
275    | Opt_TH
276    | Opt_ImplicitParams
277    | Opt_Generics
278    | Opt_ImplicitPrelude 
279    | Opt_ScopedTypeVariables
280
281    -- optimisation opts
282    | Opt_Strictness
283    | Opt_FullLaziness
284    | Opt_CSE
285    | Opt_IgnoreInterfacePragmas
286    | Opt_OmitInterfacePragmas
287    | Opt_DoLambdaEtaExpansion
288    | Opt_IgnoreAsserts
289    | Opt_DoEtaReduction
290    | Opt_CaseMerge
291    | Opt_UnboxStrictFields
292
293    deriving (Eq)
294
295 data DynFlags = DynFlags {
296   coreToDo              :: Maybe [CoreToDo], -- reserved for use with -Ofile
297   stgToDo               :: [StgToDo],
298   hscTarget             :: HscTarget,
299   hscOutName            :: String,      -- name of the output file
300   hscStubHOutName       :: String,      -- name of the .stub_h output file
301   hscStubCOutName       :: String,      -- name of the .stub_c output file
302   extCoreName           :: String,      -- name of the .core output file
303   verbosity             :: Int,         -- verbosity level
304   optLevel              :: Int,         -- optimisation level
305   maxSimplIterations    :: Int,         -- max simplifier iterations
306   ruleCheck             :: Maybe String,
307   cppFlag               :: Bool,        -- preprocess with cpp?
308   ppFlag                :: Bool,        -- preprocess with a Haskell Pp?
309   recompFlag            :: Bool,        -- True <=> recompilation checker is on
310   stolen_x86_regs       :: Int,         
311   cmdlineHcIncludes     :: [String],    -- -#includes
312   importPaths           :: [FilePath],
313
314   -- options for particular phases
315   opt_L                 :: [String],
316   opt_P                 :: [String],
317   opt_F                 :: [String],
318   opt_c                 :: [String],
319   opt_a                 :: [String],
320   opt_m                 :: [String],
321 #ifdef ILX                         
322   opt_I                 :: [String],
323   opt_i                 :: [String],
324 #endif
325
326   -- ** Package flags
327   extraPkgConfs         :: [FilePath],
328         -- The -package-conf flags given on the command line, in the order
329         -- they appeared.
330
331   readUserPkgConf       :: Bool,
332         -- Whether or not to read the user package database
333         -- (-no-user-package-conf).
334
335   packageFlags          :: [PackageFlag],
336         -- The -package and -hide-package flags from the command-line
337
338   -- ** Package state
339   pkgState              :: PackageState,
340
341   -- hsc dynamic flags
342   flags                 :: [DynFlag]
343  }
344
345 data PackageFlag
346   = ExposePackage  String
347   | HidePackage    String
348   | IgnorePackage  String
349
350 defaultHscTarget
351 #if defined(i386_TARGET_ARCH) || defined(sparc_TARGET_ARCH) || defined(powerpc_TARGET_ARCH)
352   | cGhcWithNativeCodeGen == "YES"      =  HscAsm
353 #endif
354   | otherwise                           =  HscC
355
356 defaultDynFlags = DynFlags {
357   coreToDo = Nothing, stgToDo = [], 
358   hscTarget = defaultHscTarget, 
359   hscOutName = "", 
360   hscStubHOutName = "", hscStubCOutName = "",
361   extCoreName = "",
362   verbosity             = 0, 
363   optLevel              = 0,
364   maxSimplIterations    = 4,
365   ruleCheck             = Nothing,
366   cppFlag               = False,
367   ppFlag                = False,
368   recompFlag            = True,
369   stolen_x86_regs       = 4,
370   cmdlineHcIncludes     = [],
371   importPaths           = ["."],
372   opt_L                 = [],
373   opt_P                 = [],
374   opt_F                 = [],
375   opt_c                 = [],
376   opt_a                 = [],
377   opt_m                 = [],
378 #ifdef ILX
379   opt_I                 = [],
380   opt_i                 = [],
381 #endif
382
383   extraPkgConfs         = [],
384   readUserPkgConf       = True,
385   packageFlags          = [],
386   pkgState              = error "pkgState",
387
388   flags = [ 
389             Opt_ImplicitPrelude,
390             Opt_MonomorphismRestriction,
391             Opt_Strictness,
392                         -- strictness is on by default, but this only
393                         -- applies to -O.
394             Opt_CSE,            -- similarly for CSE.
395             Opt_FullLaziness,   -- ...and for full laziness
396
397             Opt_DoLambdaEtaExpansion,
398                         -- This one is important for a tiresome reason:
399                         -- we want to make sure that the bindings for data 
400                         -- constructors are eta-expanded.  This is probably
401                         -- a good thing anyway, but it seems fragile.
402
403             -- and the default no-optimisation options:
404             Opt_IgnoreInterfacePragmas,
405             Opt_OmitInterfacePragmas
406
407            ] ++ standardWarnings
408   }
409
410 {- 
411     Verbosity levels:
412         
413     0   |   print errors & warnings only
414     1   |   minimal verbosity: print "compiling M ... done." for each module.
415     2   |   equivalent to -dshow-passes
416     3   |   equivalent to existing "ghc -v"
417     4   |   "ghc -v -ddump-most"
418     5   |   "ghc -v -ddump-all"
419 -}
420
421 dopt :: DynFlag -> DynFlags -> Bool
422 dopt f dflags  = f `elem` (flags dflags)
423
424 dopt_CoreToDo :: DynFlags -> Maybe [CoreToDo]
425 dopt_CoreToDo = coreToDo
426
427 dopt_StgToDo :: DynFlags -> [StgToDo]
428 dopt_StgToDo = stgToDo
429
430 dopt_OutName :: DynFlags -> String
431 dopt_OutName = hscOutName
432
433 dopt_HscTarget :: DynFlags -> HscTarget
434 dopt_HscTarget = hscTarget
435
436 dopt_set :: DynFlags -> DynFlag -> DynFlags
437 dopt_set dfs f = dfs{ flags = f : flags dfs }
438
439 dopt_unset :: DynFlags -> DynFlag -> DynFlags
440 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
441
442 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
443         -- We add to the options from the front, so we need to reverse the list
444 getOpts dflags opts = reverse (opts dflags)
445
446 getVerbFlag dflags 
447   | verbosity dflags >= 3  = "-v" 
448   | otherwise =  ""
449
450 -----------------------------------------------------------------------------
451 -- Setting the optimisation level
452
453 updOptLevel :: Int -> DynFlags -> DynFlags
454 -- Set dynflags appropriate to the optimisation level
455 updOptLevel n dfs
456   = if (n >= 1)
457      then dfs2{ hscTarget = HscC, optLevel = n } -- turn on -fvia-C with -O
458      else dfs2{ optLevel = n }
459   where
460    dfs1 = foldr (flip dopt_unset) dfs  remove_dopts
461    dfs2 = foldr (flip dopt_set)   dfs1 extra_dopts
462
463    extra_dopts
464         | n == 0    = opt_0_dopts
465         | otherwise = opt_1_dopts
466
467    remove_dopts
468         | n == 0    = opt_1_dopts
469         | otherwise = opt_0_dopts
470         
471 opt_0_dopts =  [ 
472         Opt_IgnoreInterfacePragmas,
473         Opt_OmitInterfacePragmas
474     ]
475
476 opt_1_dopts = [
477         Opt_IgnoreAsserts,
478         Opt_DoEtaReduction,
479         Opt_CaseMerge
480      ]
481
482 -- Core-to-core phases:
483
484 buildCoreToDo :: DynFlags -> [CoreToDo]
485 buildCoreToDo dflags = core_todo
486   where
487     opt_level     = optLevel dflags
488     max_iter      = maxSimplIterations dflags
489     strictness    = dopt Opt_Strictness dflags
490     full_laziness = dopt Opt_FullLaziness dflags
491     cse           = dopt Opt_CSE dflags
492     rule_check    = ruleCheck dflags
493
494     core_todo = 
495      if opt_level == 0 then
496       [
497         CoreDoSimplify (SimplPhase 0) [
498             MaxSimplifierIterations max_iter
499         ]
500       ]
501
502      else {- opt_level >= 1 -} [ 
503
504         -- initial simplify: mk specialiser happy: minimum effort please
505         CoreDoSimplify SimplGently [
506                         --      Simplify "gently"
507                         -- Don't inline anything till full laziness has bitten
508                         -- In particular, inlining wrappers inhibits floating
509                         -- e.g. ...(case f x of ...)...
510                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
511                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
512                         -- and now the redex (f x) isn't floatable any more
513                         -- Similarly, don't apply any rules until after full 
514                         -- laziness.  Notably, list fusion can prevent floating.
515
516             NoCaseOfCase,
517                         -- Don't do case-of-case transformations.
518                         -- This makes full laziness work better
519             MaxSimplifierIterations max_iter
520         ],
521
522         -- Specialisation is best done before full laziness
523         -- so that overloaded functions have all their dictionary lambdas manifest
524         CoreDoSpecialising,
525
526         if full_laziness then CoreDoFloatOutwards (FloatOutSw False False)
527                          else CoreDoNothing,
528
529         CoreDoFloatInwards,
530
531         CoreDoSimplify (SimplPhase 2) [
532                 -- Want to run with inline phase 2 after the specialiser to give
533                 -- maximum chance for fusion to work before we inline build/augment
534                 -- in phase 1.  This made a difference in 'ansi' where an 
535                 -- overloaded function wasn't inlined till too late.
536            MaxSimplifierIterations max_iter
537         ],
538         case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
539
540         CoreDoSimplify (SimplPhase 1) [
541                 -- Need inline-phase2 here so that build/augment get 
542                 -- inlined.  I found that spectral/hartel/genfft lost some useful
543                 -- strictness in the function sumcode' if augment is not inlined
544                 -- before strictness analysis runs
545            MaxSimplifierIterations max_iter
546         ],
547         case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
548
549         CoreDoSimplify (SimplPhase 0) [
550                 -- Phase 0: allow all Ids to be inlined now
551                 -- This gets foldr inlined before strictness analysis
552
553            MaxSimplifierIterations 3
554                 -- At least 3 iterations because otherwise we land up with
555                 -- huge dead expressions because of an infelicity in the 
556                 -- simpifier.   
557                 --      let k = BIG in foldr k z xs
558                 -- ==>  let k = BIG in letrec go = \xs -> ...(k x).... in go xs
559                 -- ==>  let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
560                 -- Don't stop now!
561
562         ],
563         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
564
565 #ifdef OLD_STRICTNESS
566         CoreDoOldStrictness
567 #endif
568         if strictness then CoreDoStrictness else CoreDoNothing,
569         CoreDoWorkerWrapper,
570         CoreDoGlomBinds,
571
572         CoreDoSimplify (SimplPhase 0) [
573            MaxSimplifierIterations max_iter
574         ],
575
576         if full_laziness then
577           CoreDoFloatOutwards (FloatOutSw False   -- Not lambdas
578                                           True)   -- Float constants
579         else CoreDoNothing,
580                 -- nofib/spectral/hartel/wang doubles in speed if you
581                 -- do full laziness late in the day.  It only happens
582                 -- after fusion and other stuff, so the early pass doesn't
583                 -- catch it.  For the record, the redex is 
584                 --        f_el22 (f_el21 r_midblock)
585
586
587         -- We want CSE to follow the final full-laziness pass, because it may
588         -- succeed in commoning up things floated out by full laziness.
589         -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
590
591         if cse then CoreCSE else CoreDoNothing,
592
593         CoreDoFloatInwards,
594
595 -- Case-liberation for -O2.  This should be after
596 -- strictness analysis and the simplification which follows it.
597
598         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
599
600         if opt_level >= 2 then
601            CoreLiberateCase
602         else
603            CoreDoNothing,
604         if opt_level >= 2 then
605            CoreDoSpecConstr
606         else
607            CoreDoNothing,
608
609         -- Final clean-up simplification:
610         CoreDoSimplify (SimplPhase 0) [
611           MaxSimplifierIterations max_iter
612         ]
613      ]
614 \end{code}
615
616 %************************************************************************
617 %*                                                                      *
618 \subsection{Warnings}
619 %*                                                                      *
620 %************************************************************************
621
622 \begin{code}
623 standardWarnings
624     = [ Opt_WarnDeprecations,
625         Opt_WarnOverlappingPatterns,
626         Opt_WarnMissingFields,
627         Opt_WarnMissingMethods,
628         Opt_WarnDuplicateExports
629       ]
630
631 minusWOpts
632     = standardWarnings ++ 
633       [ Opt_WarnUnusedBinds,
634         Opt_WarnUnusedMatches,
635         Opt_WarnUnusedImports,
636         Opt_WarnIncompletePatterns,
637         Opt_WarnDodgyImports
638       ]
639
640 minusWallOpts
641     = minusWOpts ++
642       [ Opt_WarnTypeDefaults,
643         Opt_WarnNameShadowing,
644         Opt_WarnMissingSigs,
645         Opt_WarnHiShadows,
646         Opt_WarnOrphans
647       ]
648 \end{code}
649
650 %************************************************************************
651 %*                                                                      *
652 \subsection{Classifying command-line options}
653 %*                                                                      *
654 %************************************************************************
655
656 \begin{code}
657 -- v_Statis_hsc_opts is here to avoid a circular dependency with
658 -- main/DriverState.
659 GLOBAL_VAR(v_Static_hsc_opts, [], [String])
660
661 lookUp           :: FastString -> Bool
662 lookup_def_int   :: String -> Int -> Int
663 lookup_def_float :: String -> Float -> Float
664 lookup_str       :: String -> Maybe String
665
666 unpacked_static_opts = unsafePerformIO (readIORef v_Static_hsc_opts)
667 packed_static_opts   = map mkFastString unpacked_static_opts
668
669 lookUp     sw = sw `elem` packed_static_opts
670         
671 -- (lookup_str "foo") looks for the flag -foo=X or -fooX, 
672 -- and returns the string X
673 lookup_str sw 
674    = case firstJust (map (startsWith sw) unpacked_static_opts) of
675         Just ('=' : str) -> Just str
676         Just str         -> Just str
677         Nothing          -> Nothing     
678
679 lookup_def_int sw def = case (lookup_str sw) of
680                             Nothing -> def              -- Use default
681                             Just xx -> try_read sw xx
682
683 lookup_def_float sw def = case (lookup_str sw) of
684                             Nothing -> def              -- Use default
685                             Just xx -> try_read sw xx
686
687
688 try_read :: Read a => String -> String -> a
689 -- (try_read sw str) tries to read s; if it fails, it
690 -- bleats about flag sw
691 try_read sw str
692   = case reads str of
693         ((x,_):_) -> x  -- Be forgiving: ignore trailing goop, and alternative parses
694         []        -> ghcError (UsageError ("Malformed argument " ++ str ++ " for flag " ++ sw))
695                         -- ToDo: hack alert. We should really parse the arugments
696                         --       and announce errors in a more civilised way.
697
698
699 {-
700  Putting the compiler options into temporary at-files
701  may turn out to be necessary later on if we turn hsc into
702  a pure Win32 application where I think there's a command-line
703  length limit of 255. unpacked_opts understands the @ option.
704
705 unpacked_opts :: [String]
706 unpacked_opts =
707   concat $
708   map (expandAts) $
709   map unpackFS argv  -- NOT ARGV any more: v_Static_hsc_opts
710   where
711    expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
712    expandAts l = [l]
713 -}
714 \end{code}
715
716 %************************************************************************
717 %*                                                                      *
718 \subsection{Static options}
719 %*                                                                      *
720 %************************************************************************
721
722 \begin{code}
723 -- debugging opts
724 opt_PprStyle_Debug              = lookUp  FSLIT("-dppr-debug")
725 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
726
727 -- profiling opts
728 opt_AutoSccsOnAllToplevs        = lookUp  FSLIT("-fauto-sccs-on-all-toplevs")
729 opt_AutoSccsOnExportedToplevs   = lookUp  FSLIT("-fauto-sccs-on-exported-toplevs")
730 opt_AutoSccsOnIndividualCafs    = lookUp  FSLIT("-fauto-sccs-on-individual-cafs")
731 opt_SccProfilingOn              = lookUp  FSLIT("-fscc-profiling")
732 opt_DoTickyProfiling            = lookUp  FSLIT("-fticky-ticky")
733
734 -- language opts
735 opt_DictsStrict                 = lookUp  FSLIT("-fdicts-strict")
736 opt_IrrefutableTuples           = lookUp  FSLIT("-firrefutable-tuples")
737 opt_MaxContextReductionDepth    = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
738 opt_Parallel                    = lookUp  FSLIT("-fparallel")
739 opt_SMP                         = lookUp  FSLIT("-fsmp")
740 opt_Flatten                     = lookUp  FSLIT("-fflatten")
741
742 -- optimisation opts
743 opt_NoStateHack                 = lookUp  FSLIT("-fno-state-hack")
744 opt_NoMethodSharing             = lookUp  FSLIT("-fno-method-sharing")
745 opt_CprOff                      = lookUp  FSLIT("-fcpr-off")
746 opt_RulesOff                    = lookUp  FSLIT("-frules-off")
747         -- Switch off CPR analysis in the new demand analyser
748 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold" (10::Int)
749 opt_MaxWorkerArgs               = lookup_def_int "-fmax-worker-args" (10::Int)
750
751 opt_EmitCExternDecls            = lookUp  FSLIT("-femit-extern-decls")
752 opt_EnsureSplittableC           = lookUp  FSLIT("-fglobalise-toplev-names")
753 opt_GranMacros                  = lookUp  FSLIT("-fgransim")
754 opt_HiVersion                   = read (cProjectVersionInt ++ cProjectPatchLevel) :: Int
755 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
756 opt_OmitBlackHoling             = lookUp  FSLIT("-dno-black-holing")
757 opt_RuntimeTypes                = lookUp  FSLIT("-fruntime-types")
758
759 -- Simplifier switches
760 opt_SimplNoPreInlining          = lookUp  FSLIT("-fno-pre-inlining")
761         -- NoPreInlining is there just to see how bad things
762         -- get if you don't do it!
763 opt_SimplExcessPrecision        = lookUp  FSLIT("-fexcess-precision")
764
765 -- Unfolding control
766 opt_UF_CreationThreshold        = lookup_def_int "-funfolding-creation-threshold"  (45::Int)
767 opt_UF_UseThreshold             = lookup_def_int "-funfolding-use-threshold"       (8::Int)     -- Discounts can be big
768 opt_UF_FunAppDiscount           = lookup_def_int "-funfolding-fun-discount"        (6::Int)     -- It's great to inline a fn
769 opt_UF_KeenessFactor            = lookup_def_float "-funfolding-keeness-factor"    (1.5::Float)
770 opt_UF_UpdateInPlace            = lookUp  FSLIT("-funfolding-update-in-place")
771
772 opt_UF_DearOp   = ( 4 :: Int)
773                         
774 opt_Static                      = lookUp  FSLIT("-static")
775 opt_Unregisterised              = lookUp  FSLIT("-funregisterised")
776 opt_EmitExternalCore            = lookUp  FSLIT("-fext-core")
777
778 -- Include full span info in error messages, instead of just the start position.
779 opt_ErrorSpans                  = lookUp FSLIT("-ferror-spans")
780
781 opt_PIC                         = lookUp FSLIT("-fPIC")
782 \end{code}
783
784 %************************************************************************
785 %*                                                                      *
786 \subsection{List of static hsc flags}
787 %*                                                                      *
788 %************************************************************************
789
790 \begin{code}
791 isStaticHscFlag f =
792   f `elem` [
793         "fauto-sccs-on-all-toplevs",
794         "fauto-sccs-on-exported-toplevs",
795         "fauto-sccs-on-individual-cafs",
796         "fauto-sccs-on-dicts",
797         "fscc-profiling",
798         "fticky-ticky",
799         "fall-strict",
800         "fdicts-strict",
801         "firrefutable-tuples",
802         "fparallel",
803         "fsmp",
804         "fflatten",
805         "fsemi-tagging",
806         "flet-no-escape",
807         "femit-extern-decls",
808         "fglobalise-toplev-names",
809         "fgransim",
810         "fno-hi-version-check",
811         "dno-black-holing",
812         "fno-method-sharing",
813         "fno-state-hack",
814         "fruntime-types",
815         "fno-pre-inlining",
816         "fexcess-precision",
817         "funfolding-update-in-place",
818         "static",
819         "funregisterised",
820         "fext-core",
821         "frule-check",
822         "frules-off",
823         "fcpr-off",
824         "ferror-spans",
825         "fPIC"
826         ]
827   || any (flip prefixMatch f) [
828         "fcontext-stack",
829         "fliberate-case-threshold",
830         "fmax-worker-args",
831         "fhistory-size",
832         "funfolding-creation-threshold",
833         "funfolding-use-threshold",
834         "funfolding-fun-discount",
835         "funfolding-keeness-factor"
836      ]
837 \end{code}
838
839 %************************************************************************
840 %*                                                                      *
841 \subsection{Misc functions for command-line options}
842 %*                                                                      *
843 %************************************************************************
844
845
846
847 \begin{code}
848 startsWith :: String -> String -> Maybe String
849 -- startsWith pfx (pfx++rest) = Just rest
850
851 startsWith []     str = Just str
852 startsWith (c:cs) (s:ss)
853   = if c /= s then Nothing else startsWith cs ss
854 startsWith  _     []  = Nothing
855 \end{code}