Minor refactoring of placeHolderPunRhs
[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 opt_SuppressCoercions :: Bool
188 opt_SuppressCoercions           = lookUp  (fsLit "-dsuppress-coercions")
189 opt_PprStyle_Debug  :: Bool
190 opt_PprStyle_Debug              = lookUp  (fsLit "-dppr-debug")
191 opt_PprUserLength   :: Int
192 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
193 opt_Fuel            :: Int
194 opt_Fuel                        = lookup_def_int "-dopt-fuel" maxBound
195 opt_NoDebugOutput   :: Bool
196 opt_NoDebugOutput               = lookUp  (fsLit "-dno-debug-output")
197
198
199 -- profiling opts
200 opt_SccProfilingOn :: Bool
201 opt_SccProfilingOn              = lookUp  (fsLit "-fscc-profiling")
202
203 -- Hpc opts
204 opt_Hpc :: Bool
205 opt_Hpc                         = lookUp (fsLit "-fhpc")  
206
207 -- language opts
208 opt_DictsStrict :: Bool
209 opt_DictsStrict                 = lookUp  (fsLit "-fdicts-strict")
210 opt_IrrefutableTuples :: Bool
211 opt_IrrefutableTuples           = lookUp  (fsLit "-firrefutable-tuples")
212 opt_Parallel :: Bool
213 opt_Parallel                    = lookUp  (fsLit "-fparallel")
214
215 -- optimisation opts
216 opt_DsMultiTyVar :: Bool
217 opt_DsMultiTyVar                = not (lookUp (fsLit "-fno-ds-multi-tyvar"))
218         -- On by default
219
220 opt_SimpleListLiterals :: Bool
221 opt_SimpleListLiterals          = lookUp  (fsLit "-fsimple-list-literals")
222
223 opt_NoStateHack :: Bool
224 opt_NoStateHack                 = lookUp  (fsLit "-fno-state-hack")
225
226 opt_CprOff :: Bool
227 opt_CprOff                      = lookUp  (fsLit "-fcpr-off")
228         -- Switch off CPR analysis in the new demand analyser
229 opt_MaxWorkerArgs :: Int
230 opt_MaxWorkerArgs               = lookup_def_int "-fmax-worker-args" (10::Int)
231
232 opt_GranMacros :: Bool
233 opt_GranMacros                  = lookUp  (fsLit "-fgransim")
234 opt_HiVersion :: Integer
235 opt_HiVersion                   = read (cProjectVersionInt ++ cProjectPatchLevel) :: Integer
236 opt_HistorySize :: Int
237 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
238 opt_OmitBlackHoling :: Bool
239 opt_OmitBlackHoling             = lookUp  (fsLit "-dno-black-holing")
240 opt_StubDeadValues  :: Bool
241 opt_StubDeadValues              = lookUp  (fsLit "-dstub-dead-values")
242
243 -- Simplifier switches
244 opt_SimplNoPreInlining :: Bool
245 opt_SimplNoPreInlining          = lookUp  (fsLit "-fno-pre-inlining")
246         -- NoPreInlining is there just to see how bad things
247         -- get if you don't do it!
248 opt_SimplExcessPrecision :: Bool
249 opt_SimplExcessPrecision        = lookUp  (fsLit "-fexcess-precision")
250
251 -- Unfolding control
252 -- See Note [Discounts and thresholds] in CoreUnfold
253
254 opt_UF_CreationThreshold, opt_UF_UseThreshold :: Int
255 opt_UF_DearOp, opt_UF_FunAppDiscount, opt_UF_DictDiscount :: Int
256 opt_UF_KeenessFactor :: Float
257
258 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
259 opt_UF_UseThreshold      = lookup_def_int "-funfolding-use-threshold"      (6::Int)
260 opt_UF_FunAppDiscount    = lookup_def_int "-funfolding-fun-discount"       (6::Int)
261 opt_UF_DictDiscount      = lookup_def_int "-funfolding-dict-discount"      (1::Int)
262 opt_UF_KeenessFactor     = lookup_def_float "-funfolding-keeness-factor"   (1.5::Float)
263 opt_UF_DearOp            = ( 4 :: Int)
264
265
266 -- Related to linking
267 opt_PIC :: Bool
268 #if darwin_TARGET_OS && x86_64_TARGET_ARCH
269 opt_PIC                         = True
270 #elif darwin_TARGET_OS
271 opt_PIC                         = lookUp (fsLit "-fPIC") || not opt_Static
272 #else
273 opt_PIC                         = lookUp (fsLit "-fPIC")
274 #endif
275 opt_Static :: Bool
276 opt_Static                      = lookUp  (fsLit "-static")
277 opt_Unregisterised :: Bool
278 opt_Unregisterised              = lookUp  (fsLit "-funregisterised")
279
280 -- Derived, not a real option.  Determines whether we will be compiling
281 -- info tables that reside just before the entry code, or with an
282 -- indirection to the entry code.  See TABLES_NEXT_TO_CODE in 
283 -- includes/rts/storage/InfoTables.h.
284 tablesNextToCode :: Bool
285 tablesNextToCode                = not opt_Unregisterised
286                                   && cGhcEnableTablesNextToCode == "YES"
287
288 -- Include full span info in error messages, instead of just the start position.
289 opt_ErrorSpans :: Bool
290 opt_ErrorSpans                  = lookUp (fsLit "-ferror-spans")
291
292 opt_Ticky :: Bool
293 opt_Ticky                       = lookUp (fsLit "-ticky")
294
295 -- object files and libraries to be linked in are collected here.
296 -- ToDo: perhaps this could be done without a global, it wasn't obvious
297 -- how to do it though --SDM.
298 GLOBAL_VAR(v_Ld_inputs, [],      [String])
299
300 -----------------------------------------------------------------------------
301 -- Ways
302
303 -- The central concept of a "way" is that all objects in a given
304 -- program must be compiled in the same "way".  Certain options change
305 -- parameters of the virtual machine, eg. profiling adds an extra word
306 -- to the object header, so profiling objects cannot be linked with
307 -- non-profiling objects.
308
309 -- After parsing the command-line options, we determine which "way" we
310 -- are building - this might be a combination way, eg. profiling+threaded.
311
312 -- We then find the "build-tag" associated with this way, and this
313 -- becomes the suffix used to find .hi files and libraries used in
314 -- this compilation.
315
316 data WayName
317   = WayThreaded
318   | WayDebug
319   | WayProf
320   | WayEventLog
321   | WayPar
322   | WayGran
323   | WayNDP
324   | WayDyn
325   deriving (Eq,Ord)
326
327 GLOBAL_VAR(v_Ways, [] ,[Way])
328
329 allowed_combination :: [WayName] -> Bool
330 allowed_combination way = and [ x `allowedWith` y 
331                               | x <- way, y <- way, x < y ]
332   where
333         -- Note ordering in these tests: the left argument is
334         -- <= the right argument, according to the Ord instance
335         -- on Way above.
336
337         -- dyn is allowed with everything
338         _ `allowedWith` WayDyn                  = True
339         WayDyn `allowedWith` _                  = True
340
341         -- debug is allowed with everything
342         _ `allowedWith` WayDebug                = True
343         WayDebug `allowedWith` _                = True
344
345         WayProf `allowedWith` WayNDP            = True
346         WayThreaded `allowedWith` WayProf       = True
347         WayThreaded `allowedWith` WayEventLog   = True
348         _ `allowedWith` _                       = False
349
350
351 getWayFlags :: IO [String]  -- new options
352 getWayFlags = do
353   unsorted <- readIORef v_Ways
354   let ways = sortBy (compare `on` wayName) $
355              nubBy  ((==) `on` wayName) $ unsorted
356   writeIORef v_Ways ways
357
358   if not (allowed_combination (map wayName ways))
359       then ghcError (CmdLineError $
360                     "combination not supported: "  ++
361                     foldr1 (\a b -> a ++ '/':b) 
362                     (map wayDesc ways))
363       else
364            return (concatMap wayOpts ways)
365
366 mkBuildTag :: [Way] -> String
367 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
368
369 lkupWay :: WayName -> Way
370 lkupWay w = 
371    case listToMaybe (filter ((==) w . wayName) way_details) of
372         Nothing -> error "findBuildTag"
373         Just details -> details
374
375 isRTSWay :: WayName -> Bool
376 isRTSWay = wayRTSOnly . lkupWay 
377
378 data Way = Way {
379   wayName    :: WayName,
380   wayTag     :: String,
381   wayRTSOnly :: Bool,
382   wayDesc    :: String,
383   wayOpts    :: [String]
384   }
385
386 way_details :: [ Way ]
387 way_details =
388   [ Way WayThreaded "thr" True "Threaded" [
389 #if defined(freebsd_TARGET_OS)
390 --        "-optc-pthread"
391 --      , "-optl-pthread"
392         -- FreeBSD's default threading library is the KSE-based M:N libpthread,
393         -- which GHC has some problems with.  It's currently not clear whether
394         -- the problems are our fault or theirs, but it seems that using the
395         -- alternative 1:1 threading library libthr works around it:
396           "-optl-lthr"
397 #elif defined(solaris2_TARGET_OS)
398           "-optl-lrt"
399 #endif
400         ],
401
402     Way WayDebug "debug" True "Debug" [],
403
404     Way WayDyn "dyn" False "Dynamic"
405         [ "-DDYNAMIC"
406         , "-optc-DDYNAMIC" 
407 #if defined(mingw32_TARGET_OS)
408         -- On Windows, code that is to be linked into a dynamic library must be compiled
409         --      with -fPIC. Labels not in the current package are assumed to be in a DLL 
410         --      different from the current one.
411         , "-fPIC"
412 #endif
413         ],
414
415     Way WayProf "p" False "Profiling"
416         [ "-fscc-profiling"
417         , "-DPROFILING"
418         , "-optc-DPROFILING" ],
419
420     Way WayEventLog "l" True "RTS Event Logging"
421         [ "-DTRACING"
422         , "-optc-DTRACING" ],
423
424     Way WayPar "mp" False "Parallel" 
425         [ "-fparallel"
426         , "-D__PARALLEL_HASKELL__"
427         , "-optc-DPAR"
428         , "-package concurrent"
429         , "-optc-w"
430         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
431         , "-optl-lpvm3"
432         , "-optl-lgpvm3" ],
433
434     -- at the moment we only change the RTS and could share compiler and libs!
435     Way WayPar "mt" False "Parallel ticky profiling" 
436         [ "-fparallel"
437         , "-D__PARALLEL_HASKELL__"
438         , "-optc-DPAR"
439         , "-optc-DPAR_TICKY"
440         , "-package concurrent"
441         , "-optc-w"
442         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
443         , "-optl-lpvm3"
444         , "-optl-lgpvm3" ],
445
446     Way WayPar "md" False "Distributed" 
447         [ "-fparallel"
448         , "-D__PARALLEL_HASKELL__"
449         , "-D__DISTRIBUTED_HASKELL__"
450         , "-optc-DPAR"
451         , "-optc-DDIST"
452         , "-package concurrent"
453         , "-optc-w"
454         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
455         , "-optl-lpvm3"
456         , "-optl-lgpvm3" ],
457
458     Way WayGran "mg" False "GranSim"
459         [ "-fgransim"
460         , "-D__GRANSIM__"
461         , "-optc-DGRAN"
462         , "-package concurrent" ],
463
464     Way WayNDP "ndp" False "Nested data parallelism"
465         [ "-XParr"
466         , "-fvectorise"]
467   ]