Add static flag -funfolding-dict-discount (plus layout changes)
[ghc-hetmet.git] / compiler / main / StaticFlags.hs
1 {-# OPTIONS -fno-cse #-}
2 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
3
4 -----------------------------------------------------------------------------
5 --
6 -- Static flags
7 --
8 -- Static flags can only be set once, on the command-line.  Inside GHC,
9 -- each static flag corresponds to a top-level value, usually of type Bool.
10 --
11 -- (c) The University of Glasgow 2005
12 --
13 -----------------------------------------------------------------------------
14
15 module StaticFlags (
16         staticFlags,
17         initStaticOpts,
18
19         -- Ways
20         WayName(..), Way(..), v_Ways, isRTSWay, mkBuildTag,
21
22         -- Output style options
23         opt_PprUserLength,
24         opt_SuppressUniques,
25         opt_SuppressCoercions,
26         opt_PprStyle_Debug,
27         opt_NoDebugOutput,
28
29         -- profiling opts
30         opt_SccProfilingOn,
31
32         -- Hpc opts
33         opt_Hpc,
34
35         -- language opts
36         opt_DictsStrict,
37         opt_IrrefutableTuples,
38         opt_Parallel,
39
40         -- optimisation opts
41         opt_DsMultiTyVar,
42         opt_NoStateHack,
43         opt_SimpleListLiterals,
44         opt_SpecInlineJoinPoints,
45         opt_CprOff,
46         opt_SimplNoPreInlining,
47         opt_SimplExcessPrecision,
48         opt_MaxWorkerArgs,
49
50         -- Unfolding control
51         opt_UF_CreationThreshold,
52         opt_UF_UseThreshold,
53         opt_UF_FunAppDiscount,
54         opt_UF_DictDiscount,
55         opt_UF_KeenessFactor,
56         opt_UF_DearOp,
57
58         -- Optimization fuel controls
59         opt_Fuel,
60
61         -- Related to linking
62         opt_PIC,
63         opt_Static,
64
65         -- misc opts
66         opt_IgnoreDotGhci,
67         opt_ErrorSpans,
68         opt_GranMacros,
69         opt_HiVersion,
70         opt_HistorySize,
71         opt_OmitBlackHoling,
72         opt_Unregisterised,
73         v_Ld_inputs,
74         tablesNextToCode,
75         opt_StubDeadValues,
76
77     -- For the parser
78     addOpt, removeOpt, addWay, getWayFlags, v_opt_C_ready
79   ) where
80
81 #include "HsVersions.h"
82
83 import Config
84 import FastString
85 import Util
86 import Maybes           ( firstJust )
87 import Panic
88
89 import Data.Maybe       ( listToMaybe )
90 import Data.IORef
91 import System.IO.Unsafe ( unsafePerformIO )
92 import Data.List
93
94 -----------------------------------------------------------------------------
95 -- Static flags
96
97 initStaticOpts :: IO ()
98 initStaticOpts = writeIORef v_opt_C_ready True
99
100 addOpt :: String -> IO ()
101 addOpt = consIORef v_opt_C
102
103 addWay :: WayName -> IO ()
104 addWay = consIORef v_Ways . lkupWay
105
106 removeOpt :: String -> IO ()
107 removeOpt f = do
108   fs <- readIORef v_opt_C
109   writeIORef v_opt_C $! filter (/= f) fs    
110
111 lookUp           :: FastString -> Bool
112 lookup_def_int   :: String -> Int -> Int
113 lookup_def_float :: String -> Float -> Float
114 lookup_str       :: String -> Maybe String
115
116 -- holds the static opts while they're being collected, before
117 -- being unsafely read by unpacked_static_opts below.
118 GLOBAL_VAR(v_opt_C, defaultStaticOpts, [String])
119 GLOBAL_VAR(v_opt_C_ready, False, Bool)
120
121 staticFlags :: [String]
122 staticFlags = unsafePerformIO $ do
123   ready <- readIORef v_opt_C_ready
124   if (not ready)
125         then panic "Static flags have not been initialised!\n        Please call GHC.newSession or GHC.parseStaticFlags early enough."
126         else readIORef v_opt_C
127
128 -- -static is the default
129 defaultStaticOpts :: [String]
130 defaultStaticOpts = ["-static"]
131
132 packed_static_opts :: [FastString]
133 packed_static_opts   = map mkFastString staticFlags
134
135 lookUp     sw = sw `elem` packed_static_opts
136         
137 -- (lookup_str "foo") looks for the flag -foo=X or -fooX, 
138 -- and returns the string X
139 lookup_str sw 
140    = case firstJust (map (stripPrefix sw) staticFlags) of
141         Just ('=' : str) -> Just str
142         Just str         -> Just str
143         Nothing          -> Nothing     
144
145 lookup_def_int sw def = case (lookup_str sw) of
146                             Nothing -> def              -- Use default
147                             Just xx -> try_read sw xx
148
149 lookup_def_float sw def = case (lookup_str sw) of
150                             Nothing -> def              -- Use default
151                             Just xx -> try_read sw xx
152
153
154 try_read :: Read a => String -> String -> a
155 -- (try_read sw str) tries to read s; if it fails, it
156 -- bleats about flag sw
157 try_read sw str
158   = case reads str of
159         ((x,_):_) -> x  -- Be forgiving: ignore trailing goop, and alternative parses
160         []        -> ghcError (UsageError ("Malformed argument " ++ str ++ " for flag " ++ sw))
161                         -- ToDo: hack alert. We should really parse the arugments
162                         --       and announce errors in a more civilised way.
163
164
165 {-
166  Putting the compiler options into temporary at-files
167  may turn out to be necessary later on if we turn hsc into
168  a pure Win32 application where I think there's a command-line
169  length limit of 255. unpacked_opts understands the @ option.
170
171 unpacked_opts :: [String]
172 unpacked_opts =
173   concat $
174   map (expandAts) $
175   map unpackFS argv  -- NOT ARGV any more: v_Static_hsc_opts
176   where
177    expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
178    expandAts l = [l]
179 -}
180
181 opt_IgnoreDotGhci :: Bool
182 opt_IgnoreDotGhci               = lookUp (fsLit "-ignore-dot-ghci")
183
184 -- debugging opts
185 opt_SuppressUniques :: Bool
186 opt_SuppressUniques             = lookUp  (fsLit "-dsuppress-uniques")
187 opt_SuppressCoercions :: Bool
188 opt_SuppressCoercions           = lookUp  (fsLit "-dsuppress-coercions")
189 opt_PprStyle_Debug  :: Bool
190 opt_PprStyle_Debug              = lookUp  (fsLit "-dppr-debug")
191 opt_PprUserLength   :: Int
192 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
193 opt_Fuel            :: Int
194 opt_Fuel                        = lookup_def_int "-dopt-fuel" maxBound
195 opt_NoDebugOutput   :: Bool
196 opt_NoDebugOutput               = lookUp  (fsLit "-dno-debug-output")
197
198
199 -- profiling opts
200 opt_SccProfilingOn :: Bool
201 opt_SccProfilingOn              = lookUp  (fsLit "-fscc-profiling")
202
203 -- Hpc opts
204 opt_Hpc :: Bool
205 opt_Hpc                         = lookUp (fsLit "-fhpc")  
206
207 -- language opts
208 opt_DictsStrict :: Bool
209 opt_DictsStrict                 = lookUp  (fsLit "-fdicts-strict")
210 opt_IrrefutableTuples :: Bool
211 opt_IrrefutableTuples           = lookUp  (fsLit "-firrefutable-tuples")
212 opt_Parallel :: Bool
213 opt_Parallel                    = lookUp  (fsLit "-fparallel")
214
215 -- optimisation opts
216 opt_DsMultiTyVar :: Bool
217 opt_DsMultiTyVar                = not (lookUp (fsLit "-fno-ds-multi-tyvar"))
218         -- On by default
219
220 opt_SpecInlineJoinPoints :: Bool
221 opt_SpecInlineJoinPoints        = lookUp  (fsLit "-fspec-inline-join-points")
222
223 opt_SimpleListLiterals :: Bool
224 opt_SimpleListLiterals          = lookUp  (fsLit "-fsimple-list-literals")
225
226 opt_NoStateHack :: Bool
227 opt_NoStateHack                 = lookUp  (fsLit "-fno-state-hack")
228
229 opt_CprOff :: Bool
230 opt_CprOff                      = lookUp  (fsLit "-fcpr-off")
231         -- Switch off CPR analysis in the new demand analyser
232 opt_MaxWorkerArgs :: Int
233 opt_MaxWorkerArgs               = lookup_def_int "-fmax-worker-args" (10::Int)
234
235 opt_GranMacros :: Bool
236 opt_GranMacros                  = lookUp  (fsLit "-fgransim")
237 opt_HiVersion :: Integer
238 opt_HiVersion                   = read (cProjectVersionInt ++ cProjectPatchLevel) :: Integer
239 opt_HistorySize :: Int
240 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
241 opt_OmitBlackHoling :: Bool
242 opt_OmitBlackHoling             = lookUp  (fsLit "-dno-black-holing")
243 opt_StubDeadValues  :: Bool
244 opt_StubDeadValues              = lookUp  (fsLit "-dstub-dead-values")
245
246 -- Simplifier switches
247 opt_SimplNoPreInlining :: Bool
248 opt_SimplNoPreInlining          = lookUp  (fsLit "-fno-pre-inlining")
249         -- NoPreInlining is there just to see how bad things
250         -- get if you don't do it!
251 opt_SimplExcessPrecision :: Bool
252 opt_SimplExcessPrecision        = lookUp  (fsLit "-fexcess-precision")
253
254 -- Unfolding control
255 -- See Note [Discounts and thresholds] in CoreUnfold
256
257 opt_UF_CreationThreshold, opt_UF_UseThreshold :: Int
258 opt_UF_DearOp, opt_UF_FunAppDiscount, opt_UF_DictDiscount :: Int
259 opt_UF_KeenessFactor :: Float
260
261 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
262 opt_UF_UseThreshold      = lookup_def_int "-funfolding-use-threshold"      (6::Int)
263 opt_UF_FunAppDiscount    = lookup_def_int "-funfolding-fun-discount"       (6::Int)
264 opt_UF_DictDiscount      = lookup_def_int "-funfolding-dict-discount"      (1::Int)
265 opt_UF_KeenessFactor     = lookup_def_float "-funfolding-keeness-factor"   (1.5::Float)
266 opt_UF_DearOp            = ( 4 :: Int)
267
268
269 -- Related to linking
270 opt_PIC :: Bool
271 #if darwin_TARGET_OS && x86_64_TARGET_ARCH
272 opt_PIC                         = True
273 #else
274 opt_PIC                         = lookUp (fsLit "-fPIC")
275 #endif
276 opt_Static :: Bool
277 opt_Static                      = lookUp  (fsLit "-static")
278 opt_Unregisterised :: Bool
279 opt_Unregisterised              = lookUp  (fsLit "-funregisterised")
280
281 -- Derived, not a real option.  Determines whether we will be compiling
282 -- info tables that reside just before the entry code, or with an
283 -- indirection to the entry code.  See TABLES_NEXT_TO_CODE in 
284 -- includes/rts/storage/InfoTables.h.
285 tablesNextToCode :: Bool
286 tablesNextToCode                = not opt_Unregisterised
287                                   && cGhcEnableTablesNextToCode == "YES"
288
289 -- Include full span info in error messages, instead of just the start position.
290 opt_ErrorSpans :: Bool
291 opt_ErrorSpans                  = lookUp (fsLit "-ferror-spans")
292
293
294 -- object files and libraries to be linked in are collected here.
295 -- ToDo: perhaps this could be done without a global, it wasn't obvious
296 -- how to do it though --SDM.
297 GLOBAL_VAR(v_Ld_inputs, [],      [String])
298
299 -----------------------------------------------------------------------------
300 -- Ways
301
302 -- The central concept of a "way" is that all objects in a given
303 -- program must be compiled in the same "way".  Certain options change
304 -- parameters of the virtual machine, eg. profiling adds an extra word
305 -- to the object header, so profiling objects cannot be linked with
306 -- non-profiling objects.
307
308 -- After parsing the command-line options, we determine which "way" we
309 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
310
311 -- We then find the "build-tag" associated with this way, and this
312 -- becomes the suffix used to find .hi files and libraries used in
313 -- this compilation.
314
315 data WayName
316   = WayThreaded
317   | WayDebug
318   | WayProf
319   | WayEventLog
320   | WayTicky
321   | WayPar
322   | WayGran
323   | WayNDP
324   | WayDyn
325   deriving (Eq,Ord)
326
327 GLOBAL_VAR(v_Ways, [] ,[Way])
328
329 allowed_combination :: [WayName] -> Bool
330 allowed_combination way = and [ x `allowedWith` y 
331                               | x <- way, y <- way, x < y ]
332   where
333         -- Note ordering in these tests: the left argument is
334         -- <= the right argument, according to the Ord instance
335         -- on Way above.
336
337         -- dyn is allowed with everything
338         _ `allowedWith` WayDyn                  = True
339         WayDyn `allowedWith` _                  = True
340
341         -- ticky is (now) allowed with everything
342         -- Indeed, ticky should no longer be a 'way' at all
343         _ `allowedWith` WayTicky                = True
344         WayTicky `allowedWith` _                = True
345
346         -- debug is allowed with everything
347         _ `allowedWith` WayDebug                = True
348         WayDebug `allowedWith` _                = True
349
350         WayProf `allowedWith` WayNDP            = True
351         WayThreaded `allowedWith` WayProf       = True
352         WayThreaded `allowedWith` WayEventLog   = True
353         _ `allowedWith` _                       = False
354
355
356 getWayFlags :: IO [String]  -- new options
357 getWayFlags = do
358   unsorted <- readIORef v_Ways
359   let ways = sortBy (compare `on` wayName) $
360              nubBy  ((==) `on` wayName) $ unsorted
361   writeIORef v_Ways ways
362
363   if not (allowed_combination (map wayName ways))
364       then ghcError (CmdLineError $
365                     "combination not supported: "  ++
366                     foldr1 (\a b -> a ++ '/':b) 
367                     (map wayDesc ways))
368       else
369            return (concatMap wayOpts ways)
370
371 mkBuildTag :: [Way] -> String
372 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
373
374 lkupWay :: WayName -> Way
375 lkupWay w = 
376    case listToMaybe (filter ((==) w . wayName) way_details) of
377         Nothing -> error "findBuildTag"
378         Just details -> details
379
380 isRTSWay :: WayName -> Bool
381 isRTSWay = wayRTSOnly . lkupWay 
382
383 data Way = Way {
384   wayName    :: WayName,
385   wayTag     :: String,
386   wayRTSOnly :: Bool,
387   wayDesc    :: String,
388   wayOpts    :: [String]
389   }
390
391 way_details :: [ Way ]
392 way_details =
393   [ Way WayThreaded "thr" True "Threaded" [
394 #if defined(freebsd_TARGET_OS)
395 --        "-optc-pthread"
396 --      , "-optl-pthread"
397         -- FreeBSD's default threading library is the KSE-based M:N libpthread,
398         -- which GHC has some problems with.  It's currently not clear whether
399         -- the problems are our fault or theirs, but it seems that using the
400         -- alternative 1:1 threading library libthr works around it:
401           "-optl-lthr"
402 #elif defined(solaris2_TARGET_OS)
403           "-optl-lrt"
404 #endif
405         ],
406
407     Way WayDebug "debug" True "Debug" [],
408
409     Way WayDyn "dyn" False "Dynamic"
410         [ "-DDYNAMIC"
411         , "-optc-DDYNAMIC" ],
412
413     Way WayProf "p" False "Profiling"
414         [ "-fscc-profiling"
415         , "-DPROFILING"
416         , "-optc-DPROFILING" ],
417
418     Way WayEventLog "l" True "RTS Event Logging"
419         [ "-DTRACING"
420         , "-optc-DTRACING" ],
421
422     Way WayTicky "t" True "Ticky-ticky Profiling"  
423         [ "-DTICKY_TICKY"
424         , "-optc-DTICKY_TICKY" ],
425
426     Way WayPar "mp" False "Parallel" 
427         [ "-fparallel"
428         , "-D__PARALLEL_HASKELL__"
429         , "-optc-DPAR"
430         , "-package concurrent"
431         , "-optc-w"
432         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
433         , "-optl-lpvm3"
434         , "-optl-lgpvm3" ],
435
436     -- at the moment we only change the RTS and could share compiler and libs!
437     Way WayPar "mt" False "Parallel ticky profiling" 
438         [ "-fparallel"
439         , "-D__PARALLEL_HASKELL__"
440         , "-optc-DPAR"
441         , "-optc-DPAR_TICKY"
442         , "-package concurrent"
443         , "-optc-w"
444         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
445         , "-optl-lpvm3"
446         , "-optl-lgpvm3" ],
447
448     Way WayPar "md" False "Distributed" 
449         [ "-fparallel"
450         , "-D__PARALLEL_HASKELL__"
451         , "-D__DISTRIBUTED_HASKELL__"
452         , "-optc-DPAR"
453         , "-optc-DDIST"
454         , "-package concurrent"
455         , "-optc-w"
456         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
457         , "-optl-lpvm3"
458         , "-optl-lgpvm3" ],
459
460     Way WayGran "mg" False "GranSim"
461         [ "-fgransim"
462         , "-D__GRANSIM__"
463         , "-optc-DGRAN"
464         , "-package concurrent" ],
465
466     Way WayNDP "ndp" False "Nested data parallelism"
467         [ "-XParr"
468         , "-fvectorise"]
469   ]