Whitespace only
[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_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_DictDiscount,
54         opt_UF_KeenessFactor,
55         opt_UF_DearOp,
56
57         -- Optimization fuel controls
58         opt_Fuel,
59
60         -- Related to linking
61         opt_PIC,
62         opt_Static,
63
64         -- misc opts
65         opt_IgnoreDotGhci,
66         opt_ErrorSpans,
67         opt_GranMacros,
68         opt_HiVersion,
69         opt_HistorySize,
70         opt_OmitBlackHoling,
71         opt_Unregisterised,
72         v_Ld_inputs,
73         tablesNextToCode,
74         opt_StubDeadValues,
75         opt_Ticky,
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
188 opt_SuppressCoercions :: Bool
189 opt_SuppressCoercions           = lookUp  (fsLit "-dsuppress-coercions")
190
191 opt_PprStyle_Debug  :: Bool
192 opt_PprStyle_Debug              = lookUp  (fsLit "-dppr-debug")
193
194 opt_PprUserLength   :: Int
195 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
196
197 opt_Fuel            :: Int
198 opt_Fuel                        = lookup_def_int "-dopt-fuel" maxBound
199
200 opt_NoDebugOutput   :: Bool
201 opt_NoDebugOutput               = lookUp  (fsLit "-dno-debug-output")
202
203
204 -- profiling opts
205 opt_SccProfilingOn :: Bool
206 opt_SccProfilingOn              = lookUp  (fsLit "-fscc-profiling")
207
208 -- Hpc opts
209 opt_Hpc :: Bool
210 opt_Hpc                         = lookUp (fsLit "-fhpc")  
211
212 -- language opts
213 opt_DictsStrict :: Bool
214 opt_DictsStrict                 = lookUp  (fsLit "-fdicts-strict")
215 opt_IrrefutableTuples :: Bool
216 opt_IrrefutableTuples           = lookUp  (fsLit "-firrefutable-tuples")
217 opt_Parallel :: Bool
218 opt_Parallel                    = lookUp  (fsLit "-fparallel")
219
220 -- optimisation opts
221 opt_DsMultiTyVar :: Bool
222 opt_DsMultiTyVar                = not (lookUp (fsLit "-fno-ds-multi-tyvar"))
223         -- On by default
224
225 opt_SimpleListLiterals :: Bool
226 opt_SimpleListLiterals          = lookUp  (fsLit "-fsimple-list-literals")
227
228 opt_NoStateHack :: Bool
229 opt_NoStateHack                 = lookUp  (fsLit "-fno-state-hack")
230
231 opt_CprOff :: Bool
232 opt_CprOff                      = lookUp  (fsLit "-fcpr-off")
233         -- Switch off CPR analysis in the new demand analyser
234 opt_MaxWorkerArgs :: Int
235 opt_MaxWorkerArgs               = lookup_def_int "-fmax-worker-args" (10::Int)
236
237 opt_GranMacros :: Bool
238 opt_GranMacros                  = lookUp  (fsLit "-fgransim")
239 opt_HiVersion :: Integer
240 opt_HiVersion                   = read (cProjectVersionInt ++ cProjectPatchLevel) :: Integer
241 opt_HistorySize :: Int
242 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
243 opt_OmitBlackHoling :: Bool
244 opt_OmitBlackHoling             = lookUp  (fsLit "-dno-black-holing")
245 opt_StubDeadValues  :: Bool
246 opt_StubDeadValues              = lookUp  (fsLit "-dstub-dead-values")
247
248 -- Simplifier switches
249 opt_SimplNoPreInlining :: Bool
250 opt_SimplNoPreInlining          = lookUp  (fsLit "-fno-pre-inlining")
251         -- NoPreInlining is there just to see how bad things
252         -- get if you don't do it!
253 opt_SimplExcessPrecision :: Bool
254 opt_SimplExcessPrecision        = lookUp  (fsLit "-fexcess-precision")
255
256 -- Unfolding control
257 -- See Note [Discounts and thresholds] in CoreUnfold
258
259 opt_UF_CreationThreshold, opt_UF_UseThreshold :: Int
260 opt_UF_DearOp, opt_UF_FunAppDiscount, opt_UF_DictDiscount :: Int
261 opt_UF_KeenessFactor :: Float
262
263 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
264 opt_UF_UseThreshold      = lookup_def_int "-funfolding-use-threshold"      (6::Int)
265 opt_UF_FunAppDiscount    = lookup_def_int "-funfolding-fun-discount"       (6::Int)
266 opt_UF_DictDiscount      = lookup_def_int "-funfolding-dict-discount"      (1::Int)
267 opt_UF_KeenessFactor     = lookup_def_float "-funfolding-keeness-factor"   (1.5::Float)
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 #elif darwin_TARGET_OS
276 opt_PIC                         = lookUp (fsLit "-fPIC") || not opt_Static
277 #else
278 opt_PIC                         = lookUp (fsLit "-fPIC")
279 #endif
280 opt_Static :: Bool
281 opt_Static                      = lookUp  (fsLit "-static")
282 opt_Unregisterised :: Bool
283 opt_Unregisterised              = lookUp  (fsLit "-funregisterised")
284
285 -- Derived, not a real option.  Determines whether we will be compiling
286 -- info tables that reside just before the entry code, or with an
287 -- indirection to the entry code.  See TABLES_NEXT_TO_CODE in 
288 -- includes/rts/storage/InfoTables.h.
289 tablesNextToCode :: Bool
290 tablesNextToCode                = not opt_Unregisterised
291                                   && cGhcEnableTablesNextToCode == "YES"
292
293 -- Include full span info in error messages, instead of just the start position.
294 opt_ErrorSpans :: Bool
295 opt_ErrorSpans                  = lookUp (fsLit "-ferror-spans")
296
297 opt_Ticky :: Bool
298 opt_Ticky                       = lookUp (fsLit "-ticky")
299
300 -- object files and libraries to be linked in are collected here.
301 -- ToDo: perhaps this could be done without a global, it wasn't obvious
302 -- how to do it though --SDM.
303 GLOBAL_VAR(v_Ld_inputs, [],      [String])
304
305 -----------------------------------------------------------------------------
306 -- Ways
307
308 -- The central concept of a "way" is that all objects in a given
309 -- program must be compiled in the same "way".  Certain options change
310 -- parameters of the virtual machine, eg. profiling adds an extra word
311 -- to the object header, so profiling objects cannot be linked with
312 -- non-profiling objects.
313
314 -- After parsing the command-line options, we determine which "way" we
315 -- are building - this might be a combination way, eg. profiling+threaded.
316
317 -- We then find the "build-tag" associated with this way, and this
318 -- becomes the suffix used to find .hi files and libraries used in
319 -- this compilation.
320
321 data WayName
322   = WayThreaded
323   | WayDebug
324   | WayProf
325   | WayEventLog
326   | WayPar
327   | WayGran
328   | WayNDP
329   | WayDyn
330   deriving (Eq,Ord)
331
332 GLOBAL_VAR(v_Ways, [] ,[Way])
333
334 allowed_combination :: [WayName] -> Bool
335 allowed_combination way = and [ x `allowedWith` y 
336                               | x <- way, y <- way, x < y ]
337   where
338         -- Note ordering in these tests: the left argument is
339         -- <= the right argument, according to the Ord instance
340         -- on Way above.
341
342         -- dyn is allowed with everything
343         _ `allowedWith` WayDyn                  = True
344         WayDyn `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 #if defined(mingw32_TARGET_OS)
413         -- On Windows, code that is to be linked into a dynamic library must be compiled
414         --      with -fPIC. Labels not in the current package are assumed to be in a DLL 
415         --      different from the current one.
416         , "-fPIC"
417 #endif
418         ],
419
420     Way WayProf "p" False "Profiling"
421         [ "-fscc-profiling"
422         , "-DPROFILING"
423         , "-optc-DPROFILING" ],
424
425     Way WayEventLog "l" True "RTS Event Logging"
426         [ "-DTRACING"
427         , "-optc-DTRACING" ],
428
429     Way WayPar "mp" False "Parallel" 
430         [ "-fparallel"
431         , "-D__PARALLEL_HASKELL__"
432         , "-optc-DPAR"
433         , "-package concurrent"
434         , "-optc-w"
435         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
436         , "-optl-lpvm3"
437         , "-optl-lgpvm3" ],
438
439     -- at the moment we only change the RTS and could share compiler and libs!
440     Way WayPar "mt" False "Parallel ticky profiling" 
441         [ "-fparallel"
442         , "-D__PARALLEL_HASKELL__"
443         , "-optc-DPAR"
444         , "-optc-DPAR_TICKY"
445         , "-package concurrent"
446         , "-optc-w"
447         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
448         , "-optl-lpvm3"
449         , "-optl-lgpvm3" ],
450
451     Way WayPar "md" False "Distributed" 
452         [ "-fparallel"
453         , "-D__PARALLEL_HASKELL__"
454         , "-D__DISTRIBUTED_HASKELL__"
455         , "-optc-DPAR"
456         , "-optc-DDIST"
457         , "-package concurrent"
458         , "-optc-w"
459         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
460         , "-optl-lpvm3"
461         , "-optl-lgpvm3" ],
462
463     Way WayGran "mg" False "GranSim"
464         [ "-fgransim"
465         , "-D__GRANSIM__"
466         , "-optc-DGRAN"
467         , "-package concurrent" ],
468
469     Way WayNDP "ndp" False "Nested data parallelism"
470         [ "-XParr"
471         , "-fvectorise"]
472   ]