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