[project @ 2001-02-20 15:44:26 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / DriverState.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverState.hs,v 1.28 2001/02/20 15:44:26 simonpj Exp $
3 --
4 -- Settings for the driver
5 --
6 -- (c) The University of Glasgow 2000
7 --
8 -----------------------------------------------------------------------------
9
10 module DriverState where
11
12 #include "HsVersions.h"
13
14 import CmStaticInfo
15 import CmdLineOpts
16 import DriverUtil
17 import Util
18 import Config
19 import Exception
20 import IOExts
21 #ifdef mingw32_TARGET_OS
22 import TmpFiles ( newTempName )
23 import Directory ( removeFile )
24 #endif
25 import Panic
26
27 import List
28 import Char  
29 import Monad
30
31 -----------------------------------------------------------------------------
32 -- non-configured things
33
34 cHaskell1Version = "5" -- i.e., Haskell 98
35
36 -----------------------------------------------------------------------------
37 -- Global compilation flags
38
39 -- location of compiler-related files
40 GLOBAL_VAR(v_TopDir,  clibdir, String)
41
42 -- Cpp-related flags
43 v_Hs_source_cpp_opts = global
44         [ "-D__HASKELL1__="++cHaskell1Version
45         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
46         , "-D__HASKELL98__"
47         , "-D__CONCURRENT_HASKELL__"
48         ]
49 {-# NOINLINE v_Hs_source_cpp_opts #-}
50
51 -- Keep output from intermediate phases
52 GLOBAL_VAR(v_Keep_hi_diffs,             False,          Bool)
53 GLOBAL_VAR(v_Keep_hc_files,             False,          Bool)
54 GLOBAL_VAR(v_Keep_s_files,              False,          Bool)
55 GLOBAL_VAR(v_Keep_raw_s_files,          False,          Bool)
56 GLOBAL_VAR(v_Keep_tmp_files,            False,          Bool)
57
58 -- Misc
59 GLOBAL_VAR(v_Scale_sizes_by,            1.0,            Double)
60 GLOBAL_VAR(v_Dry_run,                   False,          Bool)
61 GLOBAL_VAR(v_Static,                    True,           Bool)
62 GLOBAL_VAR(v_NoHsMain,                  False,          Bool)
63 GLOBAL_VAR(v_Recomp,                    True,           Bool)
64 GLOBAL_VAR(v_Collect_ghc_timing,        False,          Bool)
65 GLOBAL_VAR(v_Do_asm_mangling,           True,           Bool)
66 GLOBAL_VAR(v_Excess_precision,          False,          Bool)
67
68 -----------------------------------------------------------------------------
69 -- Splitting object files (for libraries)
70
71 GLOBAL_VAR(v_Split_object_files,        False,          Bool)
72 GLOBAL_VAR(v_Split_prefix,              "",             String)
73 GLOBAL_VAR(v_N_split_files,             0,              Int)
74         
75 can_split :: Bool
76 can_split =  prefixMatch "i386"    cTARGETPLATFORM
77           || prefixMatch "alpha"   cTARGETPLATFORM
78           || prefixMatch "hppa"    cTARGETPLATFORM
79           || prefixMatch "m68k"    cTARGETPLATFORM
80           || prefixMatch "mips"    cTARGETPLATFORM
81           || prefixMatch "powerpc" cTARGETPLATFORM
82           || prefixMatch "rs6000"  cTARGETPLATFORM
83           || prefixMatch "sparc"   cTARGETPLATFORM
84
85 -----------------------------------------------------------------------------
86 -- Compiler output options
87
88 defaultHscLang
89   | cGhcWithNativeCodeGen == "YES" && 
90         (prefixMatch "i386" cTARGETPLATFORM ||
91          prefixMatch "sparc" cTARGETPLATFORM)   =  HscAsm
92   | otherwise                                   =  HscC
93
94 GLOBAL_VAR(v_Output_dir,  Nothing, Maybe String)
95 GLOBAL_VAR(v_Object_suf,  Nothing, Maybe String)
96 GLOBAL_VAR(v_Output_file, Nothing, Maybe String)
97 GLOBAL_VAR(v_Output_hi,   Nothing, Maybe String)
98
99 GLOBAL_VAR(v_Ld_inputs, [],      [String])
100
101 odir_ify :: String -> IO String
102 odir_ify f = do
103   odir_opt <- readIORef v_Output_dir
104   case odir_opt of
105         Nothing -> return f
106         Just d  -> return (newdir d f)
107
108 osuf_ify :: String -> IO String
109 osuf_ify f = do
110   osuf_opt <- readIORef v_Object_suf
111   case osuf_opt of
112         Nothing -> return f
113         Just s  -> return (newsuf s f)
114
115 -----------------------------------------------------------------------------
116 -- Hi Files
117
118 GLOBAL_VAR(v_Hi_on_stdout,      False,  Bool)
119 GLOBAL_VAR(v_Hi_suf,            "hi",   String)
120
121 -----------------------------------------------------------------------------
122 -- Compiler optimisation options
123
124 GLOBAL_VAR(v_OptLevel, 0, Int)
125
126 setOptLevel :: String -> IO ()
127 setOptLevel ""              = do { writeIORef v_OptLevel 1 }
128 setOptLevel "not"           = writeIORef v_OptLevel 0
129 setOptLevel [c] | isDigit c = do
130    let level = ord c - ord '0'
131    writeIORef v_OptLevel level
132 setOptLevel s = unknownFlagErr ("-O"++s)
133
134 GLOBAL_VAR(v_minus_o2_for_C,            False, Bool)
135 GLOBAL_VAR(v_MaxSimplifierIterations,   4,     Int)
136 GLOBAL_VAR(v_StgStats,                  False, Bool)
137 GLOBAL_VAR(v_UsageSPInf,                False, Bool)  -- Off by default
138 GLOBAL_VAR(v_Strictness,                True,  Bool)
139 GLOBAL_VAR(v_CPR,                       True,  Bool)
140 GLOBAL_VAR(v_CSE,                       True,  Bool)
141
142 -- these are the static flags you get without -O.
143 hsc_minusNoO_flags =
144        [ 
145         "-fignore-interface-pragmas",
146         "-fomit-interface-pragmas",
147         "-fdo-lambda-eta-expansion",    -- This one is important for a tiresome reason:
148                                         -- we want to make sure that the bindings for data 
149                                         -- constructors are eta-expanded.  This is probably
150                                         -- a good thing anyway, but it seems fragile.
151         "-flet-no-escape"
152         ]
153
154 -- these are the static flags you get when -O is on.
155 hsc_minusO_flags =
156   [ 
157         "-ffoldr-build-on",
158         "-fdo-eta-reduction",
159         "-fdo-lambda-eta-expansion",
160         "-fcase-merge",
161         "-flet-to-case",
162         "-flet-no-escape"
163    ]
164
165 hsc_minusO2_flags = hsc_minusO_flags    -- for now
166
167 getStaticOptimisationFlags 0 = hsc_minusNoO_flags
168 getStaticOptimisationFlags 1 = hsc_minusO_flags
169 getStaticOptimisationFlags n = hsc_minusO2_flags
170
171 buildCoreToDo :: IO [CoreToDo]
172 buildCoreToDo = do
173    opt_level  <- readIORef v_OptLevel
174    max_iter   <- readIORef v_MaxSimplifierIterations
175    usageSP    <- readIORef v_UsageSPInf
176    strictness <- readIORef v_Strictness
177    cpr        <- readIORef v_CPR
178    cse        <- readIORef v_CSE
179
180    if opt_level == 0 then return
181       [
182         CoreDoSimplify (isAmongSimpl [
183             MaxSimplifierIterations max_iter
184         ])
185       ]
186
187     else {- opt_level >= 1 -} return [ 
188
189         -- initial simplify: mk specialiser happy: minimum effort please
190         CoreDoSimplify (isAmongSimpl [
191             SimplInlinePhase 0,
192                         -- Don't inline anything till full laziness has bitten
193                         -- In particular, inlining wrappers inhibits floating
194                         -- e.g. ...(case f x of ...)...
195                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
196                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
197                         -- and now the redex (f x) isn't floatable any more
198             DontApplyRules,
199                         -- Similarly, don't apply any rules until after full 
200                         -- laziness.  Notably, list fusion can prevent floating.
201             NoCaseOfCase,
202                         -- Don't do case-of-case transformations.
203                         -- This makes full laziness work better
204             MaxSimplifierIterations max_iter
205         ]),
206
207         -- Specialisation is best done before full laziness
208         -- so that overloaded functions have all their dictionary lambdas manifest
209         CoreDoSpecialising,
210
211         CoreDoFloatOutwards False{-not full-},
212         CoreDoFloatInwards,
213
214         CoreDoSimplify (isAmongSimpl [
215            SimplInlinePhase 1,
216                 -- Want to run with inline phase 1 after the specialiser to give
217                 -- maximum chance for fusion to work before we inline build/augment
218                 -- in phase 2.  This made a difference in 'ansi' where an 
219                 -- overloaded function wasn't inlined till too late.
220            MaxSimplifierIterations max_iter
221         ]),
222
223         -- infer usage information here in case we need it later.
224         -- (add more of these where you need them --KSW 1999-04)
225         if usageSP then CoreDoUSPInf else CoreDoNothing,
226
227         CoreDoSimplify (isAmongSimpl [
228                 -- Need inline-phase2 here so that build/augment get 
229                 -- inlined.  I found that spectral/hartel/genfft lost some useful
230                 -- strictness in the function sumcode' if augment is not inlined
231                 -- before strictness analysis runs
232            SimplInlinePhase 2,
233            MaxSimplifierIterations max_iter
234         ]),
235
236         CoreDoSimplify (isAmongSimpl [
237            MaxSimplifierIterations 2
238                 -- No -finline-phase: allow all Ids to be inlined now
239                 -- This gets foldr inlined before strictness analysis
240         ]),
241
242         if strictness then CoreDoStrictness else CoreDoNothing,
243         if cpr        then CoreDoCPResult   else CoreDoNothing,
244         CoreDoWorkerWrapper,
245         CoreDoGlomBinds,
246
247         CoreDoSimplify (isAmongSimpl [
248            MaxSimplifierIterations max_iter
249                 -- No -finline-phase: allow all Ids to be inlined now
250         ]),
251
252         CoreDoFloatOutwards False{-not full-},
253                 -- nofib/spectral/hartel/wang doubles in speed if you
254                 -- do full laziness late in the day.  It only happens
255                 -- after fusion and other stuff, so the early pass doesn't
256                 -- catch it.  For the record, the redex is 
257                 --        f_el22 (f_el21 r_midblock)
258
259
260 -- Leave out lambda lifting for now
261 --        "-fsimplify", -- Tidy up results of full laziness
262 --          "[", 
263 --                "-fmax-simplifier-iterations2",
264 --          "]",
265 --        "-ffloat-outwards-full",      
266
267         -- We want CSE to follow the final full-laziness pass, because it may
268         -- succeed in commoning up things floated out by full laziness.
269         -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
270
271         if cse then CoreCSE else CoreDoNothing,
272
273         CoreDoFloatInwards,
274
275 -- Case-liberation for -O2.  This should be after
276 -- strictness analysis and the simplification which follows it.
277
278         if opt_level >= 2 then
279            CoreLiberateCase
280         else
281            CoreDoNothing,
282
283         -- Final clean-up simplification:
284         CoreDoSimplify (isAmongSimpl [
285           MaxSimplifierIterations max_iter
286                 -- No -finline-phase: allow all Ids to be inlined now
287         ])
288      ]
289
290 buildStgToDo :: IO [ StgToDo ]
291 buildStgToDo = do
292   stg_stats <- readIORef v_StgStats
293   let flags1 | stg_stats = [ D_stg_stats ]
294              | otherwise = [ ]
295
296         -- STG passes
297   ways_ <- readIORef v_Ways
298   let flags2 | WayProf `elem` ways_ = StgDoMassageForProfiling : flags1
299              | otherwise            = flags1
300
301   return flags2
302
303 -----------------------------------------------------------------------------
304 -- Paths & Libraries
305
306 split_marker = ':'   -- not configurable (ToDo)
307
308 v_Import_paths, v_Include_paths, v_Library_paths :: IORef [String]
309 GLOBAL_VAR(v_Import_paths,  ["."], [String])
310 GLOBAL_VAR(v_Include_paths, ["."], [String])
311 GLOBAL_VAR(v_Library_paths, [],  [String])
312
313 GLOBAL_VAR(v_Cmdline_libraries,   [], [String])
314
315 addToDirList :: IORef [String] -> String -> IO ()
316 addToDirList ref path
317   = do paths <- readIORef ref
318        writeIORef ref (paths ++ split split_marker path)
319
320 -----------------------------------------------------------------------------
321 -- Packages
322
323 GLOBAL_VAR(v_Path_package_config, error "path_package_config", String)
324
325 -- package list is maintained in dependency order
326 GLOBAL_VAR(v_Packages, ("std":"rts":"gmp":[]), [String])
327
328 addPackage :: String -> IO ()
329 addPackage package
330   = do pkg_details <- readIORef v_Package_details
331        case lookupPkg package pkg_details of
332           Nothing -> throwDyn (OtherError ("unknown package name: " ++ package))
333           Just details -> do
334             ps <- readIORef v_Packages
335             unless (package `elem` ps) $ do
336                 mapM_ addPackage (package_deps details)
337                 ps <- readIORef v_Packages
338                 writeIORef v_Packages (package:ps)
339
340 getPackageImportPath   :: IO [String]
341 getPackageImportPath = do
342   ps <- getPackageInfo
343   return (nub (concat (map import_dirs ps)))
344
345 getPackageIncludePath   :: IO [String]
346 getPackageIncludePath = do
347   ps <- getPackageInfo
348   return (nub (filter (not.null) (concatMap include_dirs ps)))
349
350         -- includes are in reverse dependency order (i.e. rts first)
351 getPackageCIncludes   :: IO [String]
352 getPackageCIncludes = do
353   ps <- getPackageInfo
354   return (reverse (nub (filter (not.null) (concatMap c_includes ps))))
355
356 getPackageLibraryPath  :: IO [String]
357 getPackageLibraryPath = do
358   ps <- getPackageInfo
359   return (nub (concat (map library_dirs ps)))
360
361 getPackageLibraries    :: IO [String]
362 getPackageLibraries = do
363   ps <- getPackageInfo
364   tag <- readIORef v_Build_tag
365   let suffix = if null tag then "" else '_':tag
366   return (concat (
367         map (\p -> map (++suffix) (hs_libraries p) ++ extra_libraries p) ps
368      ))
369
370 getPackageExtraGhcOpts :: IO [String]
371 getPackageExtraGhcOpts = do
372   ps <- getPackageInfo
373   return (concatMap extra_ghc_opts ps)
374
375 getPackageExtraCcOpts  :: IO [String]
376 getPackageExtraCcOpts = do
377   ps <- getPackageInfo
378   return (concatMap extra_cc_opts ps)
379
380 getPackageExtraLdOpts  :: IO [String]
381 getPackageExtraLdOpts = do
382   ps <- getPackageInfo
383   return (concatMap extra_ld_opts ps)
384
385 getPackageInfo :: IO [Package]
386 getPackageInfo = do
387   ps <- readIORef v_Packages
388   getPackageDetails ps
389
390 getPackageDetails :: [String] -> IO [Package]
391 getPackageDetails ps = do
392   pkg_details <- readIORef v_Package_details
393   return [ pkg | p <- ps, Just pkg <- [ lookupPkg p pkg_details ] ]
394
395 GLOBAL_VAR(v_Package_details, (error "package_details"), [Package])
396
397 lookupPkg :: String -> [Package] -> Maybe Package
398 lookupPkg nm ps
399    = case [p | p <- ps, name p == nm] of
400         []    -> Nothing
401         (p:_) -> Just p
402 -----------------------------------------------------------------------------
403 -- Ways
404
405 -- The central concept of a "way" is that all objects in a given
406 -- program must be compiled in the same "way".  Certain options change
407 -- parameters of the virtual machine, eg. profiling adds an extra word
408 -- to the object header, so profiling objects cannot be linked with
409 -- non-profiling objects.
410
411 -- After parsing the command-line options, we determine which "way" we
412 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
413
414 -- We then find the "build-tag" associated with this way, and this
415 -- becomes the suffix used to find .hi files and libraries used in
416 -- this compilation.
417
418 GLOBAL_VAR(v_Build_tag, "", String)
419
420 data WayName
421   = WayProf
422   | WayUnreg
423   | WayTicky
424   | WayPar
425   | WayGran
426   | WaySMP
427   | WayDebug
428   | WayUser_a
429   | WayUser_b
430   | WayUser_c
431   | WayUser_d
432   | WayUser_e
433   | WayUser_f
434   | WayUser_g
435   | WayUser_h
436   | WayUser_i
437   | WayUser_j
438   | WayUser_k
439   | WayUser_l
440   | WayUser_m
441   | WayUser_n
442   | WayUser_o
443   | WayUser_A
444   | WayUser_B
445   deriving (Eq,Ord)
446
447 GLOBAL_VAR(v_Ways, [] ,[WayName])
448
449 allowed_combination way = way `elem` combs
450   where  -- the sub-lists must be ordered according to WayName, 
451          -- because findBuildTag sorts them
452     combs                = [ [WayProf,WayUnreg], [WayProf,WaySMP] ]
453
454 findBuildTag :: IO [String]  -- new options
455 findBuildTag = do
456   way_names <- readIORef v_Ways
457   case sort way_names of
458      []  -> do  writeIORef v_Build_tag ""
459                 return []
460
461      [w] -> do let details = lkupWay w
462                writeIORef v_Build_tag (wayTag details)
463                return (wayOpts details)
464
465      ws  -> if not (allowed_combination ws)
466                 then throwDyn (OtherError $
467                                 "combination not supported: "  ++
468                                 foldr1 (\a b -> a ++ '/':b) 
469                                 (map (wayName . lkupWay) ws))
470                 else let stuff = map lkupWay ws
471                          tag   = concat (map wayTag stuff)
472                          flags = map wayOpts stuff
473                      in do
474                      writeIORef v_Build_tag tag
475                      return (concat flags)
476
477 lkupWay w = 
478    case lookup w way_details of
479         Nothing -> error "findBuildTag"
480         Just details -> details
481
482 data Way = Way {
483   wayTag   :: String,
484   wayName  :: String,
485   wayOpts  :: [String]
486   }
487
488 way_details :: [ (WayName, Way) ]
489 way_details =
490   [ (WayProf, Way  "p" "Profiling"  
491         [ "-fscc-profiling"
492         , "-DPROFILING"
493         , "-optc-DPROFILING"
494         , "-fvia-C" ]),
495
496     (WayTicky, Way  "t" "Ticky-ticky Profiling"  
497         [ "-fticky-ticky"
498         , "-DTICKY_TICKY"
499         , "-optc-DTICKY_TICKY"
500         , "-fvia-C" ]),
501
502     (WayUnreg, Way  "u" "Unregisterised" 
503         unregFlags ),
504
505     (WayPar, Way  "mp" "Parallel" 
506         [ "-fparallel"
507         , "-D__PARALLEL_HASKELL__"
508         , "-optc-DPAR"
509         , "-package concurrent"
510         , "-fvia-C" ]),
511
512     (WayGran, Way  "mg" "Gransim" 
513         [ "-fgransim"
514         , "-D__GRANSIM__"
515         , "-optc-DGRAN"
516         , "-package concurrent"
517         , "-fvia-C" ]),
518
519     (WaySMP, Way  "s" "SMP"
520         [ "-fsmp"
521         , "-optc-pthread"
522         , "-optl-pthread"
523         , "-optc-DSMP"
524         , "-fvia-C" ]),
525
526     (WayUser_a,  Way  "a"  "User way 'a'"  ["$WAY_a_REAL_OPTS"]),       
527     (WayUser_b,  Way  "b"  "User way 'b'"  ["$WAY_b_REAL_OPTS"]),       
528     (WayUser_c,  Way  "c"  "User way 'c'"  ["$WAY_c_REAL_OPTS"]),       
529     (WayUser_d,  Way  "d"  "User way 'd'"  ["$WAY_d_REAL_OPTS"]),       
530     (WayUser_e,  Way  "e"  "User way 'e'"  ["$WAY_e_REAL_OPTS"]),       
531     (WayUser_f,  Way  "f"  "User way 'f'"  ["$WAY_f_REAL_OPTS"]),       
532     (WayUser_g,  Way  "g"  "User way 'g'"  ["$WAY_g_REAL_OPTS"]),       
533     (WayUser_h,  Way  "h"  "User way 'h'"  ["$WAY_h_REAL_OPTS"]),       
534     (WayUser_i,  Way  "i"  "User way 'i'"  ["$WAY_i_REAL_OPTS"]),       
535     (WayUser_j,  Way  "j"  "User way 'j'"  ["$WAY_j_REAL_OPTS"]),       
536     (WayUser_k,  Way  "k"  "User way 'k'"  ["$WAY_k_REAL_OPTS"]),       
537     (WayUser_l,  Way  "l"  "User way 'l'"  ["$WAY_l_REAL_OPTS"]),       
538     (WayUser_m,  Way  "m"  "User way 'm'"  ["$WAY_m_REAL_OPTS"]),       
539     (WayUser_n,  Way  "n"  "User way 'n'"  ["$WAY_n_REAL_OPTS"]),       
540     (WayUser_o,  Way  "o"  "User way 'o'"  ["$WAY_o_REAL_OPTS"]),       
541     (WayUser_A,  Way  "A"  "User way 'A'"  ["$WAY_A_REAL_OPTS"]),       
542     (WayUser_B,  Way  "B"  "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
543   ]
544
545 unregFlags = 
546    [ "-optc-DNO_REGS"
547    , "-optc-DUSE_MINIINTERPRETER"
548    , "-fno-asm-mangling"
549    , "-funregisterised"
550    , "-fvia-C" ]
551
552 -----------------------------------------------------------------------------
553 -- Programs for particular phases
554
555 GLOBAL_VAR(v_Pgm_L,   error "pgm_L", String)
556 GLOBAL_VAR(v_Pgm_P,   cRAWCPP,       String)
557 GLOBAL_VAR(v_Pgm_c,   cGCC,          String)
558 GLOBAL_VAR(v_Pgm_m,   error "pgm_m", String)
559 GLOBAL_VAR(v_Pgm_s,   error "pgm_s", String)
560 GLOBAL_VAR(v_Pgm_a,   cGCC,          String)
561 GLOBAL_VAR(v_Pgm_l,   cGCC,          String)
562 GLOBAL_VAR(v_Pgm_dll, cMkDLL,        String)
563
564 GLOBAL_VAR(v_Opt_dep,    [], [String])
565 GLOBAL_VAR(v_Anti_opt_C, [], [String])
566 GLOBAL_VAR(v_Opt_C,      [], [String])
567 GLOBAL_VAR(v_Opt_l,      [], [String])
568 GLOBAL_VAR(v_Opt_dll,    [], [String])
569
570 getStaticOpts :: IORef [String] -> IO [String]
571 getStaticOpts ref = readIORef ref >>= return . reverse