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