Adjust inlining heursitics
[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"       (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/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   | WayEventLog
324   | WayTicky
325   | WayPar
326   | WayGran
327   | WayNDP
328   | WayUser_a
329   | WayUser_b
330   | WayUser_c
331   | WayUser_d
332   | WayUser_e
333   | WayUser_f
334   | WayUser_g
335   | WayUser_h
336   | WayUser_i
337   | WayUser_j
338   | WayUser_k
339   | WayUser_l
340   | WayUser_m
341   | WayUser_n
342   | WayUser_o
343   | WayUser_A
344   | WayUser_B
345   deriving (Eq,Ord)
346
347 GLOBAL_VAR(v_Ways, [] ,[WayName])
348
349 allowed_combination :: [WayName] -> Bool
350 allowed_combination way = and [ x `allowedWith` y 
351                               | x <- way, y <- way, x < y ]
352   where
353         -- Note ordering in these tests: the left argument is
354         -- <= the right argument, according to the Ord instance
355         -- on Way above.
356
357         -- debug is allowed with everything
358         _ `allowedWith` WayDebug                = True
359         WayDebug `allowedWith` _                = True
360
361         WayProf `allowedWith` WayNDP            = True
362         WayThreaded `allowedWith` WayProf       = True
363         WayThreaded `allowedWith` WayEventLog   = True
364         _ `allowedWith` _                       = False
365
366
367 findBuildTag :: IO [String]  -- new options
368 findBuildTag = do
369   way_names <- readIORef v_Ways
370   let ws = sort (nub way_names)
371
372   if not (allowed_combination ws)
373       then ghcError (CmdLineError $
374                     "combination not supported: "  ++
375                     foldr1 (\a b -> a ++ '/':b) 
376                     (map (wayName . lkupWay) ws))
377       else let ways    = map lkupWay ws
378                tag     = mkBuildTag (filter (not.wayRTSOnly) ways)
379                rts_tag = mkBuildTag ways
380                flags   = map wayOpts ways
381            in do
382            writeIORef v_Build_tag tag
383            writeIORef v_RTS_Build_tag rts_tag
384            return (concat flags)
385
386
387
388 mkBuildTag :: [Way] -> String
389 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
390
391 lkupWay :: WayName -> Way
392 lkupWay w = 
393    case lookup w way_details of
394         Nothing -> error "findBuildTag"
395         Just details -> details
396
397 isRTSWay :: WayName -> Bool
398 isRTSWay = wayRTSOnly . lkupWay 
399
400 data Way = Way {
401   wayTag     :: String,
402   wayRTSOnly :: Bool,
403   wayName    :: String,
404   wayOpts    :: [String]
405   }
406
407 way_details :: [ (WayName, Way) ]
408 way_details =
409   [ (WayThreaded, Way "thr" True "Threaded" [
410 #if defined(freebsd_TARGET_OS)
411 --        "-optc-pthread"
412 --      , "-optl-pthread"
413         -- FreeBSD's default threading library is the KSE-based M:N libpthread,
414         -- which GHC has some problems with.  It's currently not clear whether
415         -- the problems are our fault or theirs, but it seems that using the
416         -- alternative 1:1 threading library libthr works around it:
417           "-optl-lthr"
418 #elif defined(solaris2_TARGET_OS)
419           "-optl-lrt"
420 #endif
421         ] ),
422
423     (WayDebug, Way "debug" True "Debug" [] ),
424
425     (WayProf, Way  "p" False "Profiling"
426         [ "-fscc-profiling"
427         , "-DPROFILING"
428         , "-optc-DPROFILING" ]),
429
430     (WayEventLog, Way  "l" True "RTS Event Logging"
431         [ "-DEVENTLOG"
432         , "-optc-DEVENTLOG" ]),
433
434     (WayTicky, Way  "t" True "Ticky-ticky Profiling"  
435         [ "-DTICKY_TICKY"
436         , "-optc-DTICKY_TICKY" ]),
437
438     -- optl's below to tell linker where to find the PVM library -- HWL
439     (WayPar, Way  "mp" False "Parallel" 
440         [ "-fparallel"
441         , "-D__PARALLEL_HASKELL__"
442         , "-optc-DPAR"
443         , "-package concurrent"
444         , "-optc-w"
445         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
446         , "-optl-lpvm3"
447         , "-optl-lgpvm3" ]),
448
449     -- at the moment we only change the RTS and could share compiler and libs!
450     (WayPar, Way  "mt" False "Parallel ticky profiling" 
451         [ "-fparallel"
452         , "-D__PARALLEL_HASKELL__"
453         , "-optc-DPAR"
454         , "-optc-DPAR_TICKY"
455         , "-package concurrent"
456         , "-optc-w"
457         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
458         , "-optl-lpvm3"
459         , "-optl-lgpvm3" ]),
460
461     (WayPar, Way  "md" False "Distributed" 
462         [ "-fparallel"
463         , "-D__PARALLEL_HASKELL__"
464         , "-D__DISTRIBUTED_HASKELL__"
465         , "-optc-DPAR"
466         , "-optc-DDIST"
467         , "-package concurrent"
468         , "-optc-w"
469         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
470         , "-optl-lpvm3"
471         , "-optl-lgpvm3" ]),
472
473     (WayGran, Way  "mg" False "GranSim"
474         [ "-fgransim"
475         , "-D__GRANSIM__"
476         , "-optc-DGRAN"
477         , "-package concurrent" ]),
478
479     (WayNDP, Way  "ndp" False "Nested data parallelism"
480         [ "-XParr"
481         , "-fvectorise"]),
482
483     (WayUser_a,  Way  "a"  False "User way 'a'"  ["$WAY_a_REAL_OPTS"]), 
484     (WayUser_b,  Way  "b"  False "User way 'b'"  ["$WAY_b_REAL_OPTS"]), 
485     (WayUser_c,  Way  "c"  False "User way 'c'"  ["$WAY_c_REAL_OPTS"]), 
486     (WayUser_d,  Way  "d"  False "User way 'd'"  ["$WAY_d_REAL_OPTS"]), 
487     (WayUser_e,  Way  "e"  False "User way 'e'"  ["$WAY_e_REAL_OPTS"]), 
488     (WayUser_f,  Way  "f"  False "User way 'f'"  ["$WAY_f_REAL_OPTS"]), 
489     (WayUser_g,  Way  "g"  False "User way 'g'"  ["$WAY_g_REAL_OPTS"]), 
490     (WayUser_h,  Way  "h"  False "User way 'h'"  ["$WAY_h_REAL_OPTS"]), 
491     (WayUser_i,  Way  "i"  False "User way 'i'"  ["$WAY_i_REAL_OPTS"]), 
492     (WayUser_j,  Way  "j"  False "User way 'j'"  ["$WAY_j_REAL_OPTS"]), 
493     (WayUser_k,  Way  "k"  False "User way 'k'"  ["$WAY_k_REAL_OPTS"]), 
494     (WayUser_l,  Way  "l"  False "User way 'l'"  ["$WAY_l_REAL_OPTS"]), 
495     (WayUser_m,  Way  "m"  False "User way 'm'"  ["$WAY_m_REAL_OPTS"]), 
496     (WayUser_n,  Way  "n"  False "User way 'n'"  ["$WAY_n_REAL_OPTS"]), 
497     (WayUser_o,  Way  "o"  False "User way 'o'"  ["$WAY_o_REAL_OPTS"]), 
498     (WayUser_A,  Way  "A"  False "User way 'A'"  ["$WAY_A_REAL_OPTS"]), 
499     (WayUser_B,  Way  "B"  False "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
500   ]
501