1 -----------------------------------------------------------------------------
5 -- Static flags can only be set once, on the command-line. Inside GHC,
6 -- each static flag corresponds to a top-level value, usually of type Bool.
8 -- (c) The University of Glasgow 2005
10 -----------------------------------------------------------------------------
18 WayName(..), v_Ways, v_Build_tag, v_RTS_Build_tag, isRTSWay,
20 -- Output style options
26 opt_AutoSccsOnAllToplevs,
27 opt_AutoSccsOnExportedToplevs,
28 opt_AutoSccsOnIndividualCafs,
37 opt_IrrefutableTuples,
43 opt_SpecInlineJoinPoints,
45 opt_SimplNoPreInlining,
46 opt_SimplExcessPrecision,
50 opt_UF_CreationThreshold,
52 opt_UF_FunAppDiscount,
73 #include "HsVersions.h"
79 import Maybes ( firstJust )
82 import Control.Exception ( throwDyn )
84 import System.IO.Unsafe ( unsafePerformIO )
85 import Control.Monad ( when )
86 import Data.Char ( isDigit )
89 -----------------------------------------------------------------------------
92 parseStaticFlags :: [String] -> IO [String]
93 parseStaticFlags args = do
94 ready <- readIORef v_opt_C_ready
95 when ready $ throwDyn (ProgramError "Too late for parseStaticFlags: call it before newSession")
97 (leftover, errs) <- processArgs static_flags args
98 when (not (null errs)) $ throwDyn (UsageError (unlines errs))
100 -- deal with the way flags: the way (eg. prof) gives rise to
101 -- further flags, some of which might be static.
102 way_flags <- findBuildTag
104 -- if we're unregisterised, add some more flags
105 let unreg_flags | cGhcUnregisterised == "YES" = unregFlags
108 (more_leftover, errs) <- processArgs static_flags (unreg_flags ++ way_flags)
110 -- see sanity code in staticOpts
111 writeIORef v_opt_C_ready True
113 -- TABLES_NEXT_TO_CODE affects the info table layout.
114 -- Be careful to do this *after* all processArgs,
115 -- because evaluating tablesNextToCode involves looking at the global
116 -- static flags. Those pesky global variables...
117 let cg_flags | tablesNextToCode = ["-optc-DTABLES_NEXT_TO_CODE"]
120 -- HACK: -fexcess-precision is both a static and a dynamic flag. If
121 -- the static flag parser has slurped it, we must return it as a
122 -- leftover too. ToDo: make -fexcess-precision dynamic only.
123 let excess_prec | opt_SimplExcessPrecision = ["-fexcess-precision"]
126 when (not (null errs)) $ ghcError (UsageError (unlines errs))
127 return (excess_prec++cg_flags++more_leftover++leftover)
129 initStaticOpts :: IO ()
130 initStaticOpts = writeIORef v_opt_C_ready True
132 static_flags :: [(String, OptKind IO)]
133 -- All the static flags should appear in this list. It describes how each
134 -- static flag should be processed. Two main purposes:
135 -- (a) if a command-line flag doesn't appear in the list, GHC can complain
136 -- (b) a command-line flag may remove, or add, other flags; e.g. the "-fno-X" things
138 -- The common (PassFlag addOpt) action puts the static flag into the bunch of
139 -- things that are searched up by the top-level definitions like
140 -- opt_foo = lookUp (fsLit "-dfoo")
142 -- Note that ordering is important in the following list: any flag which
143 -- is a prefix flag (i.e. HasArg, Prefix, OptPrefix, AnySuffix) will override
144 -- flags further down the list with the same prefix.
147 ------- GHCi -------------------------------------------------------
148 ( "ignore-dot-ghci", PassFlag addOpt )
149 , ( "read-dot-ghci" , NoArg (removeOpt "-ignore-dot-ghci") )
151 ------- ways --------------------------------------------------------
152 , ( "prof" , NoArg (addWay WayProf) )
153 , ( "ticky" , NoArg (addWay WayTicky) )
154 , ( "parallel" , NoArg (addWay WayPar) )
155 , ( "gransim" , NoArg (addWay WayGran) )
156 , ( "smp" , NoArg (addWay WayThreaded) ) -- backwards compat.
157 , ( "debug" , NoArg (addWay WayDebug) )
158 , ( "ndp" , NoArg (addWay WayNDP) )
159 , ( "threaded" , NoArg (addWay WayThreaded) )
162 ------ Debugging ----------------------------------------------------
163 , ( "dppr-debug", PassFlag addOpt )
164 , ( "dsuppress-uniques", PassFlag addOpt )
165 , ( "dppr-user-length", AnySuffix addOpt )
166 -- rest of the debugging flags are dynamic
168 --------- Profiling --------------------------------------------------
169 , ( "auto-all" , NoArg (addOpt "-fauto-sccs-on-all-toplevs") )
170 , ( "auto" , NoArg (addOpt "-fauto-sccs-on-exported-toplevs") )
171 , ( "caf-all" , NoArg (addOpt "-fauto-sccs-on-individual-cafs") )
172 -- "ignore-sccs" doesn't work (ToDo)
174 , ( "no-auto-all" , NoArg (removeOpt "-fauto-sccs-on-all-toplevs") )
175 , ( "no-auto" , NoArg (removeOpt "-fauto-sccs-on-exported-toplevs") )
176 , ( "no-caf-all" , NoArg (removeOpt "-fauto-sccs-on-individual-cafs") )
178 ------- Miscellaneous -----------------------------------------------
179 , ( "no-link-chk" , NoArg (return ()) ) -- ignored for backwards compat
181 ----- Linker --------------------------------------------------------
182 , ( "static" , PassFlag addOpt )
183 , ( "dynamic" , NoArg (removeOpt "-static") )
184 , ( "rdynamic" , NoArg (return ()) ) -- ignored for compat w/ gcc
186 ----- RTS opts ------------------------------------------------------
187 , ( "H" , HasArg (setHeapSize . fromIntegral . decodeSize) )
188 , ( "Rghc-timing" , NoArg (enableTimingStats) )
190 ------ Compiler flags -----------------------------------------------
191 -- All other "-fno-<blah>" options cancel out "-f<blah>" on the hsc cmdline
192 , ( "fno-", PrefixPred (\s -> isStaticFlag ("f"++s))
193 (\s -> removeOpt ("-f"++s)) )
195 -- Pass all remaining "-f<blah>" options to hsc
196 , ( "f", AnySuffixPred (isStaticFlag) addOpt )
199 addOpt :: String -> IO ()
200 addOpt = consIORef v_opt_C
202 addWay :: WayName -> IO ()
203 addWay = consIORef v_Ways
205 removeOpt :: String -> IO ()
207 fs <- readIORef v_opt_C
208 writeIORef v_opt_C $! filter (/= f) fs
210 lookUp :: FastString -> Bool
211 lookup_def_int :: String -> Int -> Int
212 lookup_def_float :: String -> Float -> Float
213 lookup_str :: String -> Maybe String
215 -- holds the static opts while they're being collected, before
216 -- being unsafely read by unpacked_static_opts below.
217 GLOBAL_VAR(v_opt_C, defaultStaticOpts, [String])
218 GLOBAL_VAR(v_opt_C_ready, False, Bool)
220 staticFlags :: [String]
221 staticFlags = unsafePerformIO $ do
222 ready <- readIORef v_opt_C_ready
224 then panic "Static flags have not been initialised!\n Please call GHC.newSession or GHC.parseStaticFlags early enough."
225 else readIORef v_opt_C
227 -- -static is the default
228 defaultStaticOpts :: [String]
229 defaultStaticOpts = ["-static"]
231 packed_static_opts :: [FastString]
232 packed_static_opts = map mkFastString staticFlags
234 lookUp sw = sw `elem` packed_static_opts
236 -- (lookup_str "foo") looks for the flag -foo=X or -fooX,
237 -- and returns the string X
239 = case firstJust (map (startsWith sw) staticFlags) of
240 Just ('=' : str) -> Just str
244 lookup_def_int sw def = case (lookup_str sw) of
245 Nothing -> def -- Use default
246 Just xx -> try_read sw xx
248 lookup_def_float sw def = case (lookup_str sw) of
249 Nothing -> def -- Use default
250 Just xx -> try_read sw xx
253 try_read :: Read a => String -> String -> a
254 -- (try_read sw str) tries to read s; if it fails, it
255 -- bleats about flag sw
258 ((x,_):_) -> x -- Be forgiving: ignore trailing goop, and alternative parses
259 [] -> ghcError (UsageError ("Malformed argument " ++ str ++ " for flag " ++ sw))
260 -- ToDo: hack alert. We should really parse the arugments
261 -- and announce errors in a more civilised way.
265 Putting the compiler options into temporary at-files
266 may turn out to be necessary later on if we turn hsc into
267 a pure Win32 application where I think there's a command-line
268 length limit of 255. unpacked_opts understands the @ option.
270 unpacked_opts :: [String]
274 map unpackFS argv -- NOT ARGV any more: v_Static_hsc_opts
276 expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
280 opt_IgnoreDotGhci :: Bool
281 opt_IgnoreDotGhci = lookUp (fsLit "-ignore-dot-ghci")
284 opt_SuppressUniques :: Bool
285 opt_SuppressUniques = lookUp (fsLit "-dsuppress-uniques")
286 opt_PprStyle_Debug :: Bool
287 opt_PprStyle_Debug = lookUp (fsLit "-dppr-debug")
288 opt_PprUserLength :: Int
289 opt_PprUserLength = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
292 opt_AutoSccsOnAllToplevs :: Bool
293 opt_AutoSccsOnAllToplevs = lookUp (fsLit "-fauto-sccs-on-all-toplevs")
294 opt_AutoSccsOnExportedToplevs :: Bool
295 opt_AutoSccsOnExportedToplevs = lookUp (fsLit "-fauto-sccs-on-exported-toplevs")
296 opt_AutoSccsOnIndividualCafs :: Bool
297 opt_AutoSccsOnIndividualCafs = lookUp (fsLit "-fauto-sccs-on-individual-cafs")
298 opt_SccProfilingOn :: Bool
299 opt_SccProfilingOn = lookUp (fsLit "-fscc-profiling")
300 opt_DoTickyProfiling :: Bool
301 opt_DoTickyProfiling = WayTicky `elem` (unsafePerformIO $ readIORef v_Ways)
305 opt_Hpc = lookUp (fsLit "-fhpc")
308 opt_DictsStrict :: Bool
309 opt_DictsStrict = lookUp (fsLit "-fdicts-strict")
310 opt_IrrefutableTuples :: Bool
311 opt_IrrefutableTuples = lookUp (fsLit "-firrefutable-tuples")
313 opt_Parallel = lookUp (fsLit "-fparallel")
316 opt_SpecInlineJoinPoints :: Bool
317 opt_SpecInlineJoinPoints = lookUp (fsLit "-fspec-inline-join-points")
318 opt_NoStateHack :: Bool
319 opt_NoStateHack = lookUp (fsLit "-fno-state-hack")
320 opt_NoMethodSharing :: Bool
321 opt_NoMethodSharing = lookUp (fsLit "-fno-method-sharing")
323 opt_CprOff = lookUp (fsLit "-fcpr-off")
324 -- Switch off CPR analysis in the new demand analyser
325 opt_MaxWorkerArgs :: Int
326 opt_MaxWorkerArgs = lookup_def_int "-fmax-worker-args" (10::Int)
328 opt_GranMacros :: Bool
329 opt_GranMacros = lookUp (fsLit "-fgransim")
330 opt_HiVersion :: Integer
331 opt_HiVersion = read (cProjectVersionInt ++ cProjectPatchLevel) :: Integer
332 opt_HistorySize :: Int
333 opt_HistorySize = lookup_def_int "-fhistory-size" 20
334 opt_OmitBlackHoling :: Bool
335 opt_OmitBlackHoling = lookUp (fsLit "-dno-black-holing")
337 -- Simplifier switches
338 opt_SimplNoPreInlining :: Bool
339 opt_SimplNoPreInlining = lookUp (fsLit "-fno-pre-inlining")
340 -- NoPreInlining is there just to see how bad things
341 -- get if you don't do it!
342 opt_SimplExcessPrecision :: Bool
343 opt_SimplExcessPrecision = lookUp (fsLit "-fexcess-precision")
346 opt_UF_CreationThreshold :: Int
347 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
348 opt_UF_UseThreshold :: Int
349 opt_UF_UseThreshold = lookup_def_int "-funfolding-use-threshold" (8::Int) -- Discounts can be big
350 opt_UF_FunAppDiscount :: Int
351 opt_UF_FunAppDiscount = lookup_def_int "-funfolding-fun-discount" (6::Int) -- It's great to inline a fn
352 opt_UF_KeenessFactor :: Float
353 opt_UF_KeenessFactor = lookup_def_float "-funfolding-keeness-factor" (1.5::Float)
356 opt_UF_DearOp = ( 4 :: Int)
359 #if darwin_TARGET_OS && x86_64_TARGET_ARCH
362 opt_PIC = lookUp (fsLit "-fPIC")
365 opt_Static = lookUp (fsLit "-static")
366 opt_Unregisterised :: Bool
367 opt_Unregisterised = lookUp (fsLit "-funregisterised")
369 -- Derived, not a real option. Determines whether we will be compiling
370 -- info tables that reside just before the entry code, or with an
371 -- indirection to the entry code. See TABLES_NEXT_TO_CODE in
372 -- includes/InfoTables.h.
373 tablesNextToCode :: Bool
374 tablesNextToCode = not opt_Unregisterised
375 && cGhcEnableTablesNextToCode == "YES"
377 opt_EmitExternalCore :: Bool
378 opt_EmitExternalCore = lookUp (fsLit "-fext-core")
380 -- Include full span info in error messages, instead of just the start position.
381 opt_ErrorSpans :: Bool
382 opt_ErrorSpans = lookUp (fsLit "-ferror-spans")
385 -- object files and libraries to be linked in are collected here.
386 -- ToDo: perhaps this could be done without a global, it wasn't obvious
387 -- how to do it though --SDM.
388 GLOBAL_VAR(v_Ld_inputs, [], [String])
390 isStaticFlag :: String -> Bool
393 "fauto-sccs-on-all-toplevs",
394 "fauto-sccs-on-exported-toplevs",
395 "fauto-sccs-on-individual-cafs",
398 "fspec-inline-join-points",
399 "firrefutable-tuples",
402 "fno-hi-version-check",
404 "fno-method-sharing",
410 "fhardwire-lib-paths",
418 || any (`isPrefixOf` f) [
419 "fliberate-case-threshold",
422 "funfolding-creation-threshold",
423 "funfolding-use-threshold",
424 "funfolding-fun-discount",
425 "funfolding-keeness-factor"
430 -- Misc functions for command-line options
432 startsWith :: String -> String -> Maybe String
433 -- startsWith pfx (pfx++rest) = Just rest
435 startsWith [] str = Just str
436 startsWith (c:cs) (s:ss)
437 = if c /= s then Nothing else startsWith cs ss
438 startsWith _ [] = Nothing
441 -----------------------------------------------------------------------------
442 -- convert sizes like "3.5M" into integers
444 decodeSize :: String -> Integer
446 | c == "" = truncate n
447 | c == "K" || c == "k" = truncate (n * 1000)
448 | c == "M" || c == "m" = truncate (n * 1000 * 1000)
449 | c == "G" || c == "g" = truncate (n * 1000 * 1000 * 1000)
450 | otherwise = throwDyn (CmdLineError ("can't decode size: " ++ str))
451 where (m, c) = span pred str
453 pred c = isDigit c || c == '.'
456 -----------------------------------------------------------------------------
459 foreign import ccall unsafe "setHeapSize" setHeapSize :: Int -> IO ()
460 foreign import ccall unsafe "enableTimingStats" enableTimingStats :: IO ()
462 -----------------------------------------------------------------------------
465 -- The central concept of a "way" is that all objects in a given
466 -- program must be compiled in the same "way". Certain options change
467 -- parameters of the virtual machine, eg. profiling adds an extra word
468 -- to the object header, so profiling objects cannot be linked with
469 -- non-profiling objects.
471 -- After parsing the command-line options, we determine which "way" we
472 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
474 -- We then find the "build-tag" associated with this way, and this
475 -- becomes the suffix used to find .hi files and libraries used in
478 GLOBAL_VAR(v_Build_tag, "", String)
480 -- The RTS has its own build tag, because there are some ways that
481 -- affect the RTS only.
482 GLOBAL_VAR(v_RTS_Build_tag, "", String)
511 GLOBAL_VAR(v_Ways, [] ,[WayName])
513 allowed_combination :: [WayName] -> Bool
514 allowed_combination way = and [ x `allowedWith` y
515 | x <- way, y <- way, x < y ]
517 -- Note ordering in these tests: the left argument is
518 -- <= the right argument, according to the Ord instance
521 -- debug is allowed with everything
522 _ `allowedWith` WayDebug = True
523 WayDebug `allowedWith` _ = True
525 WayProf `allowedWith` WayNDP = True
526 WayThreaded `allowedWith` WayProf = True
527 _ `allowedWith` _ = False
530 findBuildTag :: IO [String] -- new options
532 way_names <- readIORef v_Ways
533 let ws = sort (nub way_names)
535 if not (allowed_combination ws)
536 then throwDyn (CmdLineError $
537 "combination not supported: " ++
538 foldr1 (\a b -> a ++ '/':b)
539 (map (wayName . lkupWay) ws))
540 else let ways = map lkupWay ws
541 tag = mkBuildTag (filter (not.wayRTSOnly) ways)
542 rts_tag = mkBuildTag ways
543 flags = map wayOpts ways
545 writeIORef v_Build_tag tag
546 writeIORef v_RTS_Build_tag rts_tag
547 return (concat flags)
551 mkBuildTag :: [Way] -> String
552 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
554 lkupWay :: WayName -> Way
556 case lookup w way_details of
557 Nothing -> error "findBuildTag"
558 Just details -> details
560 isRTSWay :: WayName -> Bool
561 isRTSWay = wayRTSOnly . lkupWay
570 way_details :: [ (WayName, Way) ]
572 [ (WayThreaded, Way "thr" True "Threaded" [
573 #if defined(freebsd_TARGET_OS)
576 -- FreeBSD's default threading library is the KSE-based M:N libpthread,
577 -- which GHC has some problems with. It's currently not clear whether
578 -- the problems are our fault or theirs, but it seems that using the
579 -- alternative 1:1 threading library libthr works around it:
581 #elif defined(solaris2_TARGET_OS)
586 (WayDebug, Way "debug" True "Debug" [] ),
588 (WayProf, Way "p" False "Profiling"
591 , "-optc-DPROFILING" ]),
593 (WayTicky, Way "t" True "Ticky-ticky Profiling"
595 , "-optc-DTICKY_TICKY" ]),
597 -- optl's below to tell linker where to find the PVM library -- HWL
598 (WayPar, Way "mp" False "Parallel"
600 , "-D__PARALLEL_HASKELL__"
602 , "-package concurrent"
604 , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
608 -- at the moment we only change the RTS and could share compiler and libs!
609 (WayPar, Way "mt" False "Parallel ticky profiling"
611 , "-D__PARALLEL_HASKELL__"
614 , "-package concurrent"
616 , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
620 (WayPar, Way "md" False "Distributed"
622 , "-D__PARALLEL_HASKELL__"
623 , "-D__DISTRIBUTED_HASKELL__"
626 , "-package concurrent"
628 , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
632 (WayGran, Way "mg" False "GranSim"
636 , "-package concurrent" ]),
638 (WayNDP, Way "ndp" False "Nested data parallelism"
642 (WayUser_a, Way "a" False "User way 'a'" ["$WAY_a_REAL_OPTS"]),
643 (WayUser_b, Way "b" False "User way 'b'" ["$WAY_b_REAL_OPTS"]),
644 (WayUser_c, Way "c" False "User way 'c'" ["$WAY_c_REAL_OPTS"]),
645 (WayUser_d, Way "d" False "User way 'd'" ["$WAY_d_REAL_OPTS"]),
646 (WayUser_e, Way "e" False "User way 'e'" ["$WAY_e_REAL_OPTS"]),
647 (WayUser_f, Way "f" False "User way 'f'" ["$WAY_f_REAL_OPTS"]),
648 (WayUser_g, Way "g" False "User way 'g'" ["$WAY_g_REAL_OPTS"]),
649 (WayUser_h, Way "h" False "User way 'h'" ["$WAY_h_REAL_OPTS"]),
650 (WayUser_i, Way "i" False "User way 'i'" ["$WAY_i_REAL_OPTS"]),
651 (WayUser_j, Way "j" False "User way 'j'" ["$WAY_j_REAL_OPTS"]),
652 (WayUser_k, Way "k" False "User way 'k'" ["$WAY_k_REAL_OPTS"]),
653 (WayUser_l, Way "l" False "User way 'l'" ["$WAY_l_REAL_OPTS"]),
654 (WayUser_m, Way "m" False "User way 'm'" ["$WAY_m_REAL_OPTS"]),
655 (WayUser_n, Way "n" False "User way 'n'" ["$WAY_n_REAL_OPTS"]),
656 (WayUser_o, Way "o" False "User way 'o'" ["$WAY_o_REAL_OPTS"]),
657 (WayUser_A, Way "A" False "User way 'A'" ["$WAY_A_REAL_OPTS"]),
658 (WayUser_B, Way "B" False "User way 'B'" ["$WAY_B_REAL_OPTS"])
661 unregFlags :: [String]
664 , "-optc-DUSE_MINIINTERPRETER"
665 , "-fno-asm-mangling"