Use DynFlags to work out if we are doing ticky ticky profiling
[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(..), v_Ways, v_Build_tag, v_RTS_Build_tag, isRTSWay,
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         opt_EmitExternalCore,
72         v_Ld_inputs,
73         tablesNextToCode,
74         opt_StubDeadValues,
75
76     -- For the parser
77     addOpt, removeOpt, addWay, findBuildTag, v_opt_C_ready
78   ) where
79
80 #include "HsVersions.h"
81
82 import Config
83 import FastString
84 import Util
85 import Maybes           ( firstJust )
86 import Panic
87
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
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 (maybePrefixMatch 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"       (8::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/InfoTables.h.
280 tablesNextToCode :: Bool
281 tablesNextToCode                = not opt_Unregisterised
282                                   && cGhcEnableTablesNextToCode == "YES"
283
284 opt_EmitExternalCore :: Bool
285 opt_EmitExternalCore            = lookUp  (fsLit "-fext-core")
286
287 -- Include full span info in error messages, instead of just the start position.
288 opt_ErrorSpans :: Bool
289 opt_ErrorSpans                  = lookUp (fsLit "-ferror-spans")
290
291
292 -- object files and libraries to be linked in are collected here.
293 -- ToDo: perhaps this could be done without a global, it wasn't obvious
294 -- how to do it though --SDM.
295 GLOBAL_VAR(v_Ld_inputs, [],      [String])
296
297 -----------------------------------------------------------------------------
298 -- Ways
299
300 -- The central concept of a "way" is that all objects in a given
301 -- program must be compiled in the same "way".  Certain options change
302 -- parameters of the virtual machine, eg. profiling adds an extra word
303 -- to the object header, so profiling objects cannot be linked with
304 -- non-profiling objects.
305
306 -- After parsing the command-line options, we determine which "way" we
307 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
308
309 -- We then find the "build-tag" associated with this way, and this
310 -- becomes the suffix used to find .hi files and libraries used in
311 -- this compilation.
312
313 GLOBAL_VAR(v_Build_tag, "", String)
314
315 -- The RTS has its own build tag, because there are some ways that
316 -- affect the RTS only.
317 GLOBAL_VAR(v_RTS_Build_tag, "", String)
318
319 data WayName
320   = WayThreaded
321   | WayDebug
322   | WayProf
323   | WayTicky
324   | WayPar
325   | WayGran
326   | WayNDP
327   | WayUser_a
328   | WayUser_b
329   | WayUser_c
330   | WayUser_d
331   | WayUser_e
332   | WayUser_f
333   | WayUser_g
334   | WayUser_h
335   | WayUser_i
336   | WayUser_j
337   | WayUser_k
338   | WayUser_l
339   | WayUser_m
340   | WayUser_n
341   | WayUser_o
342   | WayUser_A
343   | WayUser_B
344   deriving (Eq,Ord)
345
346 GLOBAL_VAR(v_Ways, [] ,[WayName])
347
348 allowed_combination :: [WayName] -> Bool
349 allowed_combination way = and [ x `allowedWith` y 
350                               | x <- way, y <- way, x < y ]
351   where
352         -- Note ordering in these tests: the left argument is
353         -- <= the right argument, according to the Ord instance
354         -- on Way above.
355
356         -- debug is allowed with everything
357         _ `allowedWith` WayDebug                = True
358         WayDebug `allowedWith` _                = True
359
360         WayProf `allowedWith` WayNDP            = True
361         WayThreaded `allowedWith` WayProf       = True
362         _ `allowedWith` _                       = False
363
364
365 findBuildTag :: IO [String]  -- new options
366 findBuildTag = do
367   way_names <- readIORef v_Ways
368   let ws = sort (nub way_names)
369
370   if not (allowed_combination ws)
371       then ghcError (CmdLineError $
372                     "combination not supported: "  ++
373                     foldr1 (\a b -> a ++ '/':b) 
374                     (map (wayName . lkupWay) ws))
375       else let ways    = map lkupWay ws
376                tag     = mkBuildTag (filter (not.wayRTSOnly) ways)
377                rts_tag = mkBuildTag ways
378                flags   = map wayOpts ways
379            in do
380            writeIORef v_Build_tag tag
381            writeIORef v_RTS_Build_tag rts_tag
382            return (concat flags)
383
384
385
386 mkBuildTag :: [Way] -> String
387 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
388
389 lkupWay :: WayName -> Way
390 lkupWay w = 
391    case lookup w way_details of
392         Nothing -> error "findBuildTag"
393         Just details -> details
394
395 isRTSWay :: WayName -> Bool
396 isRTSWay = wayRTSOnly . lkupWay 
397
398 data Way = Way {
399   wayTag     :: String,
400   wayRTSOnly :: Bool,
401   wayName    :: String,
402   wayOpts    :: [String]
403   }
404
405 way_details :: [ (WayName, Way) ]
406 way_details =
407   [ (WayThreaded, Way "thr" True "Threaded" [
408 #if defined(freebsd_TARGET_OS)
409 --        "-optc-pthread"
410 --      , "-optl-pthread"
411         -- FreeBSD's default threading library is the KSE-based M:N libpthread,
412         -- which GHC has some problems with.  It's currently not clear whether
413         -- the problems are our fault or theirs, but it seems that using the
414         -- alternative 1:1 threading library libthr works around it:
415           "-optl-lthr"
416 #elif defined(solaris2_TARGET_OS)
417           "-optl-lrt"
418 #endif
419         ] ),
420
421     (WayDebug, Way "debug" True "Debug" [] ),
422
423     (WayProf, Way  "p" False "Profiling"
424         [ "-fscc-profiling"
425         , "-DPROFILING"
426         , "-optc-DPROFILING" ]),
427
428     (WayTicky, Way  "t" True "Ticky-ticky Profiling"  
429         [ "-DTICKY_TICKY"
430         , "-optc-DTICKY_TICKY" ]),
431
432     -- optl's below to tell linker where to find the PVM library -- HWL
433     (WayPar, Way  "mp" False "Parallel" 
434         [ "-fparallel"
435         , "-D__PARALLEL_HASKELL__"
436         , "-optc-DPAR"
437         , "-package concurrent"
438         , "-optc-w"
439         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
440         , "-optl-lpvm3"
441         , "-optl-lgpvm3" ]),
442
443     -- at the moment we only change the RTS and could share compiler and libs!
444     (WayPar, Way  "mt" False "Parallel ticky profiling" 
445         [ "-fparallel"
446         , "-D__PARALLEL_HASKELL__"
447         , "-optc-DPAR"
448         , "-optc-DPAR_TICKY"
449         , "-package concurrent"
450         , "-optc-w"
451         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
452         , "-optl-lpvm3"
453         , "-optl-lgpvm3" ]),
454
455     (WayPar, Way  "md" False "Distributed" 
456         [ "-fparallel"
457         , "-D__PARALLEL_HASKELL__"
458         , "-D__DISTRIBUTED_HASKELL__"
459         , "-optc-DPAR"
460         , "-optc-DDIST"
461         , "-package concurrent"
462         , "-optc-w"
463         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
464         , "-optl-lpvm3"
465         , "-optl-lgpvm3" ]),
466
467     (WayGran, Way  "mg" False "GranSim"
468         [ "-fgransim"
469         , "-D__GRANSIM__"
470         , "-optc-DGRAN"
471         , "-package concurrent" ]),
472
473     (WayNDP, Way  "ndp" False "Nested data parallelism"
474         [ "-XParr"
475         , "-fvectorise"]),
476
477     (WayUser_a,  Way  "a"  False "User way 'a'"  ["$WAY_a_REAL_OPTS"]), 
478     (WayUser_b,  Way  "b"  False "User way 'b'"  ["$WAY_b_REAL_OPTS"]), 
479     (WayUser_c,  Way  "c"  False "User way 'c'"  ["$WAY_c_REAL_OPTS"]), 
480     (WayUser_d,  Way  "d"  False "User way 'd'"  ["$WAY_d_REAL_OPTS"]), 
481     (WayUser_e,  Way  "e"  False "User way 'e'"  ["$WAY_e_REAL_OPTS"]), 
482     (WayUser_f,  Way  "f"  False "User way 'f'"  ["$WAY_f_REAL_OPTS"]), 
483     (WayUser_g,  Way  "g"  False "User way 'g'"  ["$WAY_g_REAL_OPTS"]), 
484     (WayUser_h,  Way  "h"  False "User way 'h'"  ["$WAY_h_REAL_OPTS"]), 
485     (WayUser_i,  Way  "i"  False "User way 'i'"  ["$WAY_i_REAL_OPTS"]), 
486     (WayUser_j,  Way  "j"  False "User way 'j'"  ["$WAY_j_REAL_OPTS"]), 
487     (WayUser_k,  Way  "k"  False "User way 'k'"  ["$WAY_k_REAL_OPTS"]), 
488     (WayUser_l,  Way  "l"  False "User way 'l'"  ["$WAY_l_REAL_OPTS"]), 
489     (WayUser_m,  Way  "m"  False "User way 'm'"  ["$WAY_m_REAL_OPTS"]), 
490     (WayUser_n,  Way  "n"  False "User way 'n'"  ["$WAY_n_REAL_OPTS"]), 
491     (WayUser_o,  Way  "o"  False "User way 'o'"  ["$WAY_o_REAL_OPTS"]), 
492     (WayUser_A,  Way  "A"  False "User way 'A'"  ["$WAY_A_REAL_OPTS"]), 
493     (WayUser_B,  Way  "B"  False "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
494   ]
495