Add -dppr-colsN to set width of dumps
[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 opt_PprCols :: Int
241 opt_PprCols                     = lookup_def_int "-dppr-cols" 100
242
243
244 opt_PprStyle_Debug  :: Bool
245 opt_PprStyle_Debug              = lookUp  (fsLit "-dppr-debug")
246
247 opt_TraceLevel :: Int
248 opt_TraceLevel = lookup_def_int "-dtrace-level" 1       -- Standard level is 1
249                                                         -- Less verbose is 0
250
251 opt_PprUserLength   :: Int
252 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
253
254 opt_Fuel            :: Int
255 opt_Fuel                        = lookup_def_int "-dopt-fuel" maxBound
256
257 opt_NoDebugOutput   :: Bool
258 opt_NoDebugOutput               = lookUp  (fsLit "-dno-debug-output")
259
260
261 -- profiling opts
262 opt_SccProfilingOn :: Bool
263 opt_SccProfilingOn              = lookUp  (fsLit "-fscc-profiling")
264
265 -- Hpc opts
266 opt_Hpc :: Bool
267 opt_Hpc                         = lookUp (fsLit "-fhpc")  
268
269 -- language opts
270 opt_DictsStrict :: Bool
271 opt_DictsStrict                 = lookUp  (fsLit "-fdicts-strict")
272
273 opt_IrrefutableTuples :: Bool
274 opt_IrrefutableTuples           = lookUp  (fsLit "-firrefutable-tuples")
275
276 opt_Parallel :: Bool
277 opt_Parallel                    = lookUp  (fsLit "-fparallel")
278
279 opt_SimpleListLiterals :: Bool
280 opt_SimpleListLiterals          = lookUp  (fsLit "-fsimple-list-literals")
281
282 opt_NoStateHack :: Bool
283 opt_NoStateHack                 = lookUp  (fsLit "-fno-state-hack")
284
285 opt_CprOff :: Bool
286 opt_CprOff                      = lookUp  (fsLit "-fcpr-off")
287         -- Switch off CPR analysis in the new demand analyser
288 opt_MaxWorkerArgs :: Int
289 opt_MaxWorkerArgs               = lookup_def_int "-fmax-worker-args" (10::Int)
290
291 opt_GranMacros :: Bool
292 opt_GranMacros                  = lookUp  (fsLit "-fgransim")
293
294 opt_HiVersion :: Integer
295 opt_HiVersion                   = read (cProjectVersionInt ++ cProjectPatchLevel) :: Integer
296
297 opt_HistorySize :: Int
298 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
299
300 opt_OmitBlackHoling :: Bool
301 opt_OmitBlackHoling             = lookUp  (fsLit "-dno-black-holing")
302
303 opt_StubDeadValues  :: Bool
304 opt_StubDeadValues              = lookUp  (fsLit "-dstub-dead-values")
305
306 -- Simplifier switches
307 opt_SimplNoPreInlining :: Bool
308 opt_SimplNoPreInlining          = lookUp  (fsLit "-fno-pre-inlining")
309         -- NoPreInlining is there just to see how bad things
310         -- get if you don't do it!
311 opt_SimplExcessPrecision :: Bool
312 opt_SimplExcessPrecision        = lookUp  (fsLit "-fexcess-precision")
313
314 -- Unfolding control
315 -- See Note [Discounts and thresholds] in CoreUnfold
316
317 opt_UF_CreationThreshold, opt_UF_UseThreshold :: Int
318 opt_UF_DearOp, opt_UF_FunAppDiscount, opt_UF_DictDiscount :: Int
319 opt_UF_KeenessFactor :: Float
320
321 opt_UF_CreationThreshold = lookup_def_int "-funfolding-creation-threshold" (45::Int)
322 opt_UF_UseThreshold      = lookup_def_int "-funfolding-use-threshold"      (6::Int)
323 opt_UF_FunAppDiscount    = lookup_def_int "-funfolding-fun-discount"       (6::Int)
324
325 opt_UF_DictDiscount      = lookup_def_int "-funfolding-dict-discount"      (3::Int)
326    -- Be fairly keen to inline a fuction if that means
327    -- we'll be able to pick the right method from a dictionary
328
329 opt_UF_KeenessFactor     = lookup_def_float "-funfolding-keeness-factor"   (1.5::Float)
330 opt_UF_DearOp            = ( 4 :: Int)
331
332
333 -- Related to linking
334 opt_PIC :: Bool
335 #if darwin_TARGET_OS && x86_64_TARGET_ARCH
336 opt_PIC                         = True
337 #elif darwin_TARGET_OS
338 opt_PIC                         = lookUp (fsLit "-fPIC") || not opt_Static
339 #else
340 opt_PIC                         = lookUp (fsLit "-fPIC")
341 #endif
342 opt_Static :: Bool
343 opt_Static                      = lookUp  (fsLit "-static")
344 opt_Unregisterised :: Bool
345 opt_Unregisterised              = lookUp  (fsLit "-funregisterised")
346
347 -- Derived, not a real option.  Determines whether we will be compiling
348 -- info tables that reside just before the entry code, or with an
349 -- indirection to the entry code.  See TABLES_NEXT_TO_CODE in 
350 -- includes/rts/storage/InfoTables.h.
351 tablesNextToCode :: Bool
352 tablesNextToCode                = not opt_Unregisterised
353                                   && cGhcEnableTablesNextToCode == "YES"
354
355 -- Include full span info in error messages, instead of just the start position.
356 opt_ErrorSpans :: Bool
357 opt_ErrorSpans                  = lookUp (fsLit "-ferror-spans")
358
359 opt_Ticky :: Bool
360 opt_Ticky                       = lookUp (fsLit "-ticky")
361
362 -- object files and libraries to be linked in are collected here.
363 -- ToDo: perhaps this could be done without a global, it wasn't obvious
364 -- how to do it though --SDM.
365 GLOBAL_VAR(v_Ld_inputs, [],      [String])
366
367 -----------------------------------------------------------------------------
368 -- Ways
369
370 -- The central concept of a "way" is that all objects in a given
371 -- program must be compiled in the same "way".  Certain options change
372 -- parameters of the virtual machine, eg. profiling adds an extra word
373 -- to the object header, so profiling objects cannot be linked with
374 -- non-profiling objects.
375
376 -- After parsing the command-line options, we determine which "way" we
377 -- are building - this might be a combination way, eg. profiling+threaded.
378
379 -- We then find the "build-tag" associated with this way, and this
380 -- becomes the suffix used to find .hi files and libraries used in
381 -- this compilation.
382
383 data WayName
384   = WayThreaded
385   | WayDebug
386   | WayProf
387   | WayEventLog
388   | WayPar
389   | WayGran
390   | WayNDP
391   | WayDyn
392   deriving (Eq,Ord)
393
394 GLOBAL_VAR(v_Ways, [] ,[Way])
395
396 allowed_combination :: [WayName] -> Bool
397 allowed_combination way = and [ x `allowedWith` y 
398                               | x <- way, y <- way, x < y ]
399   where
400         -- Note ordering in these tests: the left argument is
401         -- <= the right argument, according to the Ord instance
402         -- on Way above.
403
404         -- dyn is allowed with everything
405         _ `allowedWith` WayDyn                  = True
406         WayDyn `allowedWith` _                  = True
407
408         -- debug is allowed with everything
409         _ `allowedWith` WayDebug                = True
410         WayDebug `allowedWith` _                = True
411
412         WayProf `allowedWith` WayNDP            = True
413         WayThreaded `allowedWith` WayProf       = True
414         WayThreaded `allowedWith` WayEventLog   = True
415         _ `allowedWith` _                       = False
416
417
418 getWayFlags :: IO [String]  -- new options
419 getWayFlags = do
420   unsorted <- readIORef v_Ways
421   let ways = sortBy (compare `on` wayName) $
422              nubBy  ((==) `on` wayName) $ unsorted
423   writeIORef v_Ways ways
424
425   if not (allowed_combination (map wayName ways))
426       then ghcError (CmdLineError $
427                     "combination not supported: "  ++
428                     foldr1 (\a b -> a ++ '/':b) 
429                     (map wayDesc ways))
430       else
431            return (concatMap wayOpts ways)
432
433 mkBuildTag :: [Way] -> String
434 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
435
436 lkupWay :: WayName -> Way
437 lkupWay w = 
438    case listToMaybe (filter ((==) w . wayName) way_details) of
439         Nothing -> error "findBuildTag"
440         Just details -> details
441
442 isRTSWay :: WayName -> Bool
443 isRTSWay = wayRTSOnly . lkupWay 
444
445 data Way = Way {
446   wayName    :: WayName,
447   wayTag     :: String,
448   wayRTSOnly :: Bool,
449   wayDesc    :: String,
450   wayOpts    :: [String]
451   }
452
453 way_details :: [ Way ]
454 way_details =
455   [ Way WayThreaded "thr" True "Threaded" [
456 #if defined(freebsd_TARGET_OS)
457 --        "-optc-pthread"
458 --      , "-optl-pthread"
459         -- FreeBSD's default threading library is the KSE-based M:N libpthread,
460         -- which GHC has some problems with.  It's currently not clear whether
461         -- the problems are our fault or theirs, but it seems that using the
462         -- alternative 1:1 threading library libthr works around it:
463           "-optl-lthr"
464 #elif defined(openbsd_TARGET_OS)
465           "-optc-pthread"
466         , "-optl-pthread"
467 #elif defined(solaris2_TARGET_OS)
468           "-optl-lrt"
469 #endif
470         ],
471
472     Way WayDebug "debug" True "Debug" [],
473
474     Way WayDyn "dyn" False "Dynamic"
475         [ "-DDYNAMIC"
476         , "-optc-DDYNAMIC" 
477 #if defined(mingw32_TARGET_OS)
478         -- On Windows, code that is to be linked into a dynamic library must be compiled
479         --      with -fPIC. Labels not in the current package are assumed to be in a DLL 
480         --      different from the current one.
481         , "-fPIC"
482 #elif defined(openbsd_TARGET_OS)
483         -- Without this, linking the shared libHSffi fails because
484         -- it uses pthread mutexes.
485         , "-optl-pthread"
486 #endif
487         ],
488
489     Way WayProf "p" False "Profiling"
490         [ "-fscc-profiling"
491         , "-DPROFILING"
492         , "-optc-DPROFILING" ],
493
494     Way WayEventLog "l" True "RTS Event Logging"
495         [ "-DTRACING"
496         , "-optc-DTRACING" ],
497
498     Way WayPar "mp" False "Parallel" 
499         [ "-fparallel"
500         , "-D__PARALLEL_HASKELL__"
501         , "-optc-DPAR"
502         , "-package concurrent"
503         , "-optc-w"
504         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
505         , "-optl-lpvm3"
506         , "-optl-lgpvm3" ],
507
508     -- at the moment we only change the RTS and could share compiler and libs!
509     Way WayPar "mt" False "Parallel ticky profiling" 
510         [ "-fparallel"
511         , "-D__PARALLEL_HASKELL__"
512         , "-optc-DPAR"
513         , "-optc-DPAR_TICKY"
514         , "-package concurrent"
515         , "-optc-w"
516         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
517         , "-optl-lpvm3"
518         , "-optl-lgpvm3" ],
519
520     Way WayPar "md" False "Distributed" 
521         [ "-fparallel"
522         , "-D__PARALLEL_HASKELL__"
523         , "-D__DISTRIBUTED_HASKELL__"
524         , "-optc-DPAR"
525         , "-optc-DDIST"
526         , "-package concurrent"
527         , "-optc-w"
528         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
529         , "-optl-lpvm3"
530         , "-optl-lgpvm3" ],
531
532     Way WayGran "mg" False "GranSim"
533         [ "-fgransim"
534         , "-D__GRANSIM__"
535         , "-optc-DGRAN"
536         , "-package concurrent" ],
537
538     Way WayNDP "ndp" False "Nested data parallelism"
539         [ "-XParr"
540         , "-fvectorise"]
541   ]