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