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