0e22c0165f03d944a735f68c2325cbc43f21ea9e
[ghc-hetmet.git] / ghc / compiler / main / DriverState.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverState.hs,v 1.93 2003/06/24 12:56:44 stolz Exp $
3 --
4 -- Settings for the driver
5 --
6 -- (c) The University of Glasgow 2002
7 --
8 -----------------------------------------------------------------------------
9
10 module DriverState where
11
12 #include "../includes/config.h"
13 #include "HsVersions.h"
14
15 import ParsePkgConf     ( loadPackageConfig )
16 import SysTools         ( getTopDir )
17 import Packages
18 import CmdLineOpts
19 import DriverPhases
20 import DriverUtil
21 import UniqFM           ( eltsUFM )
22 import Util
23 import Config
24 import Panic
25
26 import DATA_IOREF       ( IORef, readIORef, writeIORef )
27 import EXCEPTION
28
29 import List
30 import Char  
31 import Monad
32 import Maybe            ( fromJust, isJust )
33 import Directory        ( doesDirectoryExist )
34
35 -----------------------------------------------------------------------------
36 -- non-configured things
37
38 cHaskell1Version = "5" -- i.e., Haskell 98
39
40 -----------------------------------------------------------------------------
41 -- GHC modes of operation
42
43 data GhcMode
44   = DoMkDependHS                        -- ghc -M
45   | DoMkDLL                             -- ghc --mk-dll
46   | StopBefore Phase                    -- ghc -E | -C | -S | -c
47   | DoMake                              -- ghc --make
48   | DoInteractive                       -- ghc --interactive
49   | DoLink                              -- [ the default ]
50   deriving (Eq,Show)
51
52 GLOBAL_VAR(v_GhcMode,     DoLink, GhcMode)
53 GLOBAL_VAR(v_GhcModeFlag, "",     String)
54
55 setMode :: GhcMode -> String -> IO ()
56 setMode m flag = do
57   old_mode <- readIORef v_GhcMode
58   old_flag <- readIORef v_GhcModeFlag
59   when (notNull old_flag && flag /= old_flag) $
60       throwDyn (UsageError 
61           ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
62   writeIORef v_GhcMode m
63   writeIORef v_GhcModeFlag flag
64
65 isCompManagerMode DoMake        = True
66 isCompManagerMode DoInteractive = True
67 isCompManagerMode _             = False
68
69 -----------------------------------------------------------------------------
70 -- Global compilation flags
71
72 -- Cpp-related flags
73 v_Hs_source_cpp_opts = global
74         [ "-D__HASKELL1__="++cHaskell1Version
75         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
76         , "-D__HASKELL98__"
77         , "-D__CONCURRENT_HASKELL__"
78         ]
79 {-# NOINLINE v_Hs_source_cpp_opts #-}
80
81
82 -- Keep output from intermediate phases
83 GLOBAL_VAR(v_Keep_hi_diffs,             False,          Bool)
84 GLOBAL_VAR(v_Keep_hc_files,             False,          Bool)
85 GLOBAL_VAR(v_Keep_s_files,              False,          Bool)
86 GLOBAL_VAR(v_Keep_raw_s_files,          False,          Bool)
87 GLOBAL_VAR(v_Keep_tmp_files,            False,          Bool)
88 #ifdef ILX
89 GLOBAL_VAR(v_Keep_il_files,             False,          Bool)
90 GLOBAL_VAR(v_Keep_ilx_files,            False,          Bool)
91 #endif
92
93 -- Misc
94 GLOBAL_VAR(v_Scale_sizes_by,            1.0,            Double)
95 GLOBAL_VAR(v_Static,                    True,           Bool)
96 GLOBAL_VAR(v_NoLink,                    False,          Bool)
97 GLOBAL_VAR(v_NoHsMain,                  False,          Bool)
98 GLOBAL_VAR(v_MainModIs,                 Nothing,        Maybe String)
99 GLOBAL_VAR(v_MainFunIs,                 Nothing,        Maybe String)
100 GLOBAL_VAR(v_Recomp,                    True,           Bool)
101 GLOBAL_VAR(v_Collect_ghc_timing,        False,          Bool)
102 GLOBAL_VAR(v_Do_asm_mangling,           True,           Bool)
103 GLOBAL_VAR(v_Excess_precision,          False,          Bool)
104 GLOBAL_VAR(v_Read_DotGHCi,              True,           Bool)
105
106 -- Preprocessor flags
107 GLOBAL_VAR(v_Hs_source_pp_opts, [], [String])
108
109 -----------------------------------------------------------------------------
110 -- Splitting object files (for libraries)
111
112 GLOBAL_VAR(v_Split_object_files,        False,          Bool)
113 GLOBAL_VAR(v_Split_info,                ("",0),         (String,Int))
114         -- The split prefix and number of files
115
116         
117 can_split :: Bool
118 can_split =  prefixMatch "i386"    cTARGETPLATFORM
119           || prefixMatch "alpha"   cTARGETPLATFORM
120           || prefixMatch "hppa"    cTARGETPLATFORM
121           || prefixMatch "m68k"    cTARGETPLATFORM
122           || prefixMatch "mips"    cTARGETPLATFORM
123           || prefixMatch "powerpc" cTARGETPLATFORM
124           || prefixMatch "rs6000"  cTARGETPLATFORM
125           || prefixMatch "sparc"   cTARGETPLATFORM
126
127 -----------------------------------------------------------------------------
128 -- Compiler output options
129
130 GLOBAL_VAR(v_Output_dir,  Nothing, Maybe String)
131 GLOBAL_VAR(v_Output_file, Nothing, Maybe String)
132 GLOBAL_VAR(v_Output_hi,   Nothing, Maybe String)
133
134 -- called to verify that the output files & directories
135 -- point somewhere valid. 
136 --
137 -- The assumption is that the directory portion of these output
138 -- options will have to exist by the time 'verifyOutputFiles'
139 -- is invoked.
140 -- 
141 verifyOutputFiles :: IO ()
142 verifyOutputFiles = do
143   odir <- readIORef v_Output_dir
144   when (isJust odir) $ do
145      let dir = fromJust odir
146      flg <- doesDirectoryExist dir
147      when (not flg) (nonExistentDir "-odir" dir)
148   ofile <- readIORef v_Output_file
149   when (isJust ofile) $ do
150      let fn = fromJust ofile
151      flg <- doesDirNameExist fn
152      when (not flg) (nonExistentDir "-o" fn)
153   ohi <- readIORef v_Output_hi
154   when (isJust ohi) $ do
155      let hi = fromJust ohi
156      flg <- doesDirNameExist hi
157      when (not flg) (nonExistentDir "-ohi" hi)
158  where
159    nonExistentDir flg dir = 
160      throwDyn (CmdLineError ("error: directory portion of " ++ 
161                              show dir ++ " does not exist (used with " ++ 
162                              show flg ++ " option.)"))
163
164 GLOBAL_VAR(v_Object_suf,  phaseInputExt Ln, String)
165 GLOBAL_VAR(v_HC_suf,      Nothing, Maybe String)
166 GLOBAL_VAR(v_Hi_dir,      Nothing, Maybe String)
167 GLOBAL_VAR(v_Hi_suf,      "hi",    String)
168
169 GLOBAL_VAR(v_Ld_inputs, [],      [String])
170
171 odir_ify :: String -> IO String
172 odir_ify f = do
173   odir_opt <- readIORef v_Output_dir
174   case odir_opt of
175         Nothing -> return f
176         Just d  -> return (replaceFilenameDirectory f d)
177
178 osuf_ify :: String -> IO String
179 osuf_ify f = do
180   osuf <- readIORef v_Object_suf
181   return (replaceFilenameSuffix f osuf)
182
183 -----------------------------------------------------------------------------
184 -- Compiler optimisation options
185
186 GLOBAL_VAR(v_OptLevel, 0, Int)
187
188 setOptLevel :: Int -> IO ()
189 setOptLevel n = do
190   when (n >= 1) $ setLang HscC          -- turn on -fvia-C with -O
191   writeIORef v_OptLevel n
192
193 GLOBAL_VAR(v_minus_o2_for_C,            False, Bool)
194 GLOBAL_VAR(v_MaxSimplifierIterations,   4,     Int)
195 GLOBAL_VAR(v_StgStats,                  False, Bool)
196 GLOBAL_VAR(v_Strictness,                True,  Bool)
197 GLOBAL_VAR(v_CSE,                       True,  Bool)
198 GLOBAL_VAR(v_RuleCheck,                 Nothing,  Maybe String)
199
200 -- these are the static flags you get without -O.
201 hsc_minusNoO_flags =
202        [ 
203         "-fignore-interface-pragmas",
204         "-fomit-interface-pragmas",
205         "-fdo-lambda-eta-expansion",    -- This one is important for a tiresome reason:
206                                         -- we want to make sure that the bindings for data 
207                                         -- constructors are eta-expanded.  This is probably
208                                         -- a good thing anyway, but it seems fragile.
209         "-flet-no-escape"
210         ]
211
212 -- these are the static flags you get when -O is on.
213 hsc_minusO_flags =
214   [ 
215         "-fignore-asserts",
216         "-ffoldr-build-on",
217         "-fdo-eta-reduction",
218         "-fdo-lambda-eta-expansion",
219         "-fcase-merge",
220         "-flet-to-case",
221         "-flet-no-escape"
222    ]
223
224 hsc_minusO2_flags = hsc_minusO_flags    -- for now
225
226 getStaticOptimisationFlags 0 = hsc_minusNoO_flags
227 getStaticOptimisationFlags 1 = hsc_minusO_flags
228 getStaticOptimisationFlags n = hsc_minusO2_flags
229
230 buildCoreToDo :: IO [CoreToDo]
231 buildCoreToDo = do
232    opt_level  <- readIORef v_OptLevel
233    max_iter   <- readIORef v_MaxSimplifierIterations
234    strictness <- readIORef v_Strictness
235    cse        <- readIORef v_CSE
236    rule_check <- readIORef v_RuleCheck
237
238    if opt_level == 0 then return
239       [
240         CoreDoSimplify (SimplPhase 0) [
241             MaxSimplifierIterations max_iter
242         ]
243       ]
244
245     else {- opt_level >= 1 -} return [ 
246
247         -- initial simplify: mk specialiser happy: minimum effort please
248         CoreDoSimplify SimplGently [
249                         --      Simplify "gently"
250                         -- Don't inline anything till full laziness has bitten
251                         -- In particular, inlining wrappers inhibits floating
252                         -- e.g. ...(case f x of ...)...
253                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
254                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
255                         -- and now the redex (f x) isn't floatable any more
256                         -- Similarly, don't apply any rules until after full 
257                         -- laziness.  Notably, list fusion can prevent floating.
258
259             NoCaseOfCase,
260                         -- Don't do case-of-case transformations.
261                         -- This makes full laziness work better
262             MaxSimplifierIterations max_iter
263         ],
264
265         -- Specialisation is best done before full laziness
266         -- so that overloaded functions have all their dictionary lambdas manifest
267         CoreDoSpecialising,
268
269         CoreDoFloatOutwards (FloatOutSw False False),
270         CoreDoFloatInwards,
271
272         CoreDoSimplify (SimplPhase 2) [
273                 -- Want to run with inline phase 2 after the specialiser to give
274                 -- maximum chance for fusion to work before we inline build/augment
275                 -- in phase 1.  This made a difference in 'ansi' where an 
276                 -- overloaded function wasn't inlined till too late.
277            MaxSimplifierIterations max_iter
278         ],
279         case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
280
281         CoreDoSimplify (SimplPhase 1) [
282                 -- Need inline-phase2 here so that build/augment get 
283                 -- inlined.  I found that spectral/hartel/genfft lost some useful
284                 -- strictness in the function sumcode' if augment is not inlined
285                 -- before strictness analysis runs
286            MaxSimplifierIterations max_iter
287         ],
288         case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
289
290         CoreDoSimplify (SimplPhase 0) [
291                 -- Phase 0: allow all Ids to be inlined now
292                 -- This gets foldr inlined before strictness analysis
293
294            MaxSimplifierIterations 3
295                 -- At least 3 iterations because otherwise we land up with
296                 -- huge dead expressions because of an infelicity in the 
297                 -- simpifier.   
298                 --      let k = BIG in foldr k z xs
299                 -- ==>  let k = BIG in letrec go = \xs -> ...(k x).... in go xs
300                 -- ==>  let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
301                 -- Don't stop now!
302
303         ],
304         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
305
306 #ifdef OLD_STRICTNESS
307         CoreDoOldStrictness
308 #endif
309         if strictness then CoreDoStrictness else CoreDoNothing,
310         CoreDoWorkerWrapper,
311         CoreDoGlomBinds,
312
313         CoreDoSimplify (SimplPhase 0) [
314            MaxSimplifierIterations max_iter
315         ],
316
317         CoreDoFloatOutwards (FloatOutSw False   -- Not lambdas
318                                         True),  -- Float constants
319                 -- nofib/spectral/hartel/wang doubles in speed if you
320                 -- do full laziness late in the day.  It only happens
321                 -- after fusion and other stuff, so the early pass doesn't
322                 -- catch it.  For the record, the redex is 
323                 --        f_el22 (f_el21 r_midblock)
324
325
326         -- We want CSE to follow the final full-laziness pass, because it may
327         -- succeed in commoning up things floated out by full laziness.
328         -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
329
330         if cse then CoreCSE else CoreDoNothing,
331
332         CoreDoFloatInwards,
333
334 -- Case-liberation for -O2.  This should be after
335 -- strictness analysis and the simplification which follows it.
336
337         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
338
339         if opt_level >= 2 then
340            CoreLiberateCase
341         else
342            CoreDoNothing,
343         if opt_level >= 2 then
344            CoreDoSpecConstr
345         else
346            CoreDoNothing,
347
348         -- Final clean-up simplification:
349         CoreDoSimplify (SimplPhase 0) [
350           MaxSimplifierIterations max_iter
351         ]
352      ]
353
354 buildStgToDo :: IO [ StgToDo ]
355 buildStgToDo = do
356   stg_stats <- readIORef v_StgStats
357   let flags1 | stg_stats = [ D_stg_stats ]
358              | otherwise = [ ]
359
360         -- STG passes
361   ways_ <- readIORef v_Ways
362   let flags2 | WayProf `elem` ways_ = StgDoMassageForProfiling : flags1
363              | otherwise            = flags1
364
365   return flags2
366
367 -----------------------------------------------------------------------------
368 -- Paths & Libraries
369
370 split_marker = ':'   -- not configurable (ToDo)
371
372 v_Import_paths, v_Include_paths, v_Library_paths :: IORef [String]
373 GLOBAL_VAR(v_Import_paths,  ["."], [String])
374 GLOBAL_VAR(v_Include_paths, ["."], [String])
375 GLOBAL_VAR(v_Library_paths, [],  [String])
376
377 #ifdef darwin_TARGET_OS
378 GLOBAL_VAR(v_Framework_paths, [], [String])
379 GLOBAL_VAR(v_Cmdline_frameworks, [], [String])
380 #endif
381
382 addToDirList :: IORef [String] -> String -> IO ()
383 addToDirList ref path
384   = do paths           <- readIORef ref
385        shiny_new_ones  <- splitUp path
386        writeIORef ref (paths ++ filter notNull shiny_new_ones)
387                 -- empty paths are ignored: there might be a trailing
388                 -- ':' in the initial list, for example.  Empty paths can
389                 -- cause confusion when they are translated into -I options
390                 -- for passing to gcc.
391   where
392     splitUp ::String -> IO [String]
393 #ifdef mingw32_TARGET_OS
394      -- 'hybrid' support for DOS-style paths in directory lists.
395      -- 
396      -- That is, if "foo:bar:baz" is used, this interpreted as
397      -- consisting of three entries, 'foo', 'bar', 'baz'.
398      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
399      -- as four elts, "c:/foo", "c:\\foo", "x", and "/bar" --
400      -- *provided* c:/foo exists and x:/bar doesn't.
401      --
402      -- Notice that no attempt is made to fully replace the 'standard'
403      -- split marker ':' with the Windows / DOS one, ';'. The reason being
404      -- that this will cause too much breakage for users & ':' will
405      -- work fine even with DOS paths, if you're not insisting on being silly.
406      -- So, use either.
407     splitUp []         = return []
408     splitUp (x:':':div:xs) 
409       | div `elem` dir_markers = do
410           let (p,rs) = findNextPath xs
411           ps  <- splitUp rs
412            {-
413              Consult the file system to check the interpretation
414              of (x:':':div:p) -- this is arguably excessive, we
415              could skip this test & just say that it is a valid
416              dir path.
417            -}
418           flg <- doesDirectoryExist (x:':':div:p)
419           if flg then
420              return ((x:':':div:p):ps)
421            else
422              return ([x]:(div:p):ps)
423     splitUp xs = do
424       let (p,rs) = findNextPath xs
425       ps <- splitUp rs
426       return (cons p ps)
427     
428     cons "" xs = xs
429     cons x  xs = x:xs
430
431     -- will be called either when we've consumed nought or the "<Drive>:/" part of
432     -- a DOS path, so splitting is just a Q of finding the next split marker.
433     findNextPath xs = 
434         case break (`elem` split_markers) xs of
435            (p, d:ds) -> (p, ds)
436            (p, xs)   -> (p, xs)
437
438     split_markers :: [Char]
439     split_markers = [':', ';']
440
441     dir_markers :: [Char]
442     dir_markers = ['/', '\\']
443
444 #else
445     splitUp xs = return (split split_marker xs)
446 #endif
447
448 -- ----------------------------------------------------------------------------
449 -- Loading the package config file
450
451 readPackageConf :: String -> IO ()
452 readPackageConf conf_file = do
453   proto_pkg_configs <- loadPackageConfig conf_file
454   top_dir           <- getTopDir
455   let pkg_configs = mungePackagePaths top_dir proto_pkg_configs
456   extendPackageConfigMap pkg_configs
457
458 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
459 -- Replace the string "$libdir" at the beginning of a path
460 -- with the current libdir (obtained from the -B option).
461 mungePackagePaths top_dir ps = map munge_pkg ps
462  where 
463   munge_pkg p = p{ import_dirs  = munge_paths (import_dirs p),
464                    include_dirs = munge_paths (include_dirs p),
465                    library_dirs = munge_paths (library_dirs p),
466                    framework_dirs = munge_paths (framework_dirs p) }
467
468   munge_paths = map munge_path
469
470   munge_path p 
471           | Just p' <- my_prefix_match "$libdir" p = top_dir ++ p'
472           | otherwise                              = p
473
474
475 -- -----------------------------------------------------------------------------
476 -- The list of packages requested on the command line
477
478 -- The package list reflects what packages were given as command-line options,
479 -- plus their dependent packages.  It is maintained in dependency order;
480 -- earlier packages may depend on later ones, but not vice versa
481 GLOBAL_VAR(v_ExplicitPackages, initPackageList, [PackageName])
482
483 initPackageList = [basePackage, rtsPackage]
484         -- basePackage is part of this list entirely because of 
485         -- wired-in names in GHCi.  See the notes on wired-in names in
486         -- Linker.linkExpr.  By putting the base backage in initPackageList
487         -- we make sure that it'll always by linked.
488
489
490 -- add a package requested from the command-line
491 addPackage :: String -> IO ()
492 addPackage package = do
493   pkg_details <- getPackageConfigMap
494   ps  <- readIORef v_ExplicitPackages
495   ps' <- add_package pkg_details ps (mkPackageName package)
496                 -- Throws an exception if it fails
497   writeIORef v_ExplicitPackages ps'
498
499 -- internal helper
500 add_package :: PackageConfigMap -> [PackageName]
501             -> PackageName -> IO [PackageName]
502 add_package pkg_details ps p    
503   | p `elem` ps -- Check if we've already added this package
504   = return ps
505   | Just details <- lookupPkg pkg_details p
506   -- Add the package's dependents also
507   = do ps' <- foldM (add_package pkg_details) ps (packageDependents details)
508        return (p : ps')
509   | otherwise
510   = throwDyn (CmdLineError ("unknown package name: " ++ packageNameString p))
511
512
513 -- -----------------------------------------------------------------------------
514 -- Extracting information from the packages in scope
515
516 -- Many of these functions take a list of packages: in those cases,
517 -- the list is expected to contain the "dependent packages",
518 -- i.e. those packages that were found to be depended on by the
519 -- current module/program.  These can be auto or non-auto packages, it
520 -- doesn't really matter.  The list is always combined with the list
521 -- of explicit (command-line) packages to determine which packages to
522 -- use.
523
524 getPackageImportPath :: IO [String]
525 getPackageImportPath = do
526   ps <- getExplicitAndAutoPackageConfigs
527                   -- import dirs are always derived from the 'auto' 
528                   -- packages as well as the explicit ones
529   return (nub (filter notNull (concatMap import_dirs ps)))
530
531 getPackageIncludePath :: [PackageName] -> IO [String]
532 getPackageIncludePath pkgs = do
533   ps <- getExplicitPackagesAnd pkgs
534   return (nub (filter notNull (concatMap include_dirs ps)))
535
536         -- includes are in reverse dependency order (i.e. rts first)
537 getPackageCIncludes :: [PackageConfig] -> IO [String]
538 getPackageCIncludes pkg_configs = do
539   return (reverse (nub (filter notNull (concatMap c_includes pkg_configs))))
540
541 getPackageLibraryPath :: [PackageName] -> IO [String]
542 getPackageLibraryPath pkgs = do 
543   ps <- getExplicitPackagesAnd pkgs
544   return (nub (filter notNull (concatMap library_dirs ps)))
545
546 getPackageLinkOpts :: [PackageName] -> IO [String]
547 getPackageLinkOpts pkgs = do
548   ps <- getExplicitPackagesAnd pkgs
549   tag <- readIORef v_Build_tag
550   static <- readIORef v_Static
551   let 
552         imp        = if static then "" else "_imp"
553         suffix     = if null tag then "" else '_':tag
554         libs p     = map (++suffix) (hACK (hs_libraries p)) ++ extra_libraries p
555         imp_libs p = map (++imp) (libs p)
556         all_opts p = map ("-l" ++) (imp_libs p) ++ extra_ld_opts p
557
558   return (concat (map all_opts ps))
559   where
560      -- This is a totally horrible (temporary) hack, for Win32.  Problem is
561      -- that package.conf for Win32 says that the main prelude lib is 
562      -- split into HSbase1, HSbase2 and HSbase3, which is needed due to a bug
563      -- in the GNU linker (PEi386 backend). However, we still only
564      -- have HSbase.a for static linking, not HSbase{1,2,3}.a
565      -- getPackageLibraries is called to find the .a's to add to the static
566      -- link line.  On Win32, this hACK detects HSbase{1,2,3} and 
567      -- replaces them with HSbase, so static linking still works.
568      -- Libraries needed for dynamic (GHCi) linking are discovered via
569      -- different route (in InteractiveUI.linkPackage).
570      -- See driver/PackageSrc.hs for the HSbase1/HSbase2 split definition.
571      -- THIS IS A STRICTLY TEMPORARY HACK (famous last words ...)
572      -- JRS 04 Sept 01: Same appalling hack for HSwin32[1,2]
573      -- KAA 29 Mar  02: Same appalling hack for HSobjectio[1,2,3,4]
574      hACK libs
575 #      if !defined(mingw32_TARGET_OS) && !defined(cygwin32_TARGET_OS)
576        = libs
577 #      else
578        = if   "HSbase1" `elem` libs && "HSbase2" `elem` libs && "HSbase3" `elem` libs
579          then "HSbase" : filter (not.(isPrefixOf "HSbase")) libs
580          else
581          if   "HSwin321" `elem` libs && "HSwin322" `elem` libs
582          then "HSwin32" : filter (not.(isPrefixOf "HSwin32")) libs
583          else 
584          if   "HSobjectio1" `elem` libs && "HSobjectio2" `elem` libs && "HSobjectio3" `elem` libs && "HSobjectio4" `elem` libs
585          then "HSobjectio" : filter (not.(isPrefixOf "HSobjectio")) libs
586          else 
587          libs
588 #      endif
589
590 getPackageExtraGhcOpts :: IO [String]
591 getPackageExtraGhcOpts = do
592   ps <- getExplicitAndAutoPackageConfigs
593   return (concatMap extra_ghc_opts ps)
594
595 getPackageExtraCcOpts :: [PackageName] -> IO [String]
596 getPackageExtraCcOpts pkgs = do
597   ps <- getExplicitPackagesAnd pkgs
598   return (concatMap extra_cc_opts ps)
599
600 #ifdef darwin_TARGET_OS
601 getPackageFrameworkPath  :: [PackageName] -> IO [String]
602 getPackageFrameworkPath pkgs = do
603   ps <- getExplicitPackagesAnd pkgs
604   return (nub (filter notNull (concatMap framework_dirs ps)))
605
606 getPackageFrameworks  :: [PackageName] -> IO [String]
607 getPackageFrameworks pkgs = do
608   ps <- getExplicitPackagesAnd pkgs
609   return (concatMap extra_frameworks ps)
610 #endif
611
612 -- -----------------------------------------------------------------------------
613 -- Package Utils
614
615 getExplicitPackagesAnd :: [PackageName] -> IO [PackageConfig]
616 getExplicitPackagesAnd pkg_names = do
617   pkg_map <- getPackageConfigMap
618   expl <- readIORef v_ExplicitPackages
619   all_pkgs <- foldM (add_package pkg_map) expl pkg_names
620   getPackageDetails all_pkgs
621
622 -- return all packages, including both the auto packages and the explicit ones
623 getExplicitAndAutoPackageConfigs :: IO [PackageConfig]
624 getExplicitAndAutoPackageConfigs = do
625   pkg_map <- getPackageConfigMap
626   let auto_packages = [ mkPackageName (name p) | p <- eltsUFM pkg_map, auto p ]
627   getExplicitPackagesAnd auto_packages
628
629 -----------------------------------------------------------------------------
630 -- Ways
631
632 -- The central concept of a "way" is that all objects in a given
633 -- program must be compiled in the same "way".  Certain options change
634 -- parameters of the virtual machine, eg. profiling adds an extra word
635 -- to the object header, so profiling objects cannot be linked with
636 -- non-profiling objects.
637
638 -- After parsing the command-line options, we determine which "way" we
639 -- are building - this might be a combination way, eg. profiling+ticky-ticky.
640
641 -- We then find the "build-tag" associated with this way, and this
642 -- becomes the suffix used to find .hi files and libraries used in
643 -- this compilation.
644
645 GLOBAL_VAR(v_Build_tag, "", String)
646
647 data WayName
648   = WayProf
649   | WayUnreg
650   | WayTicky
651   | WayPar
652   | WayGran
653   | WaySMP
654   | WayNDP
655   | WayDebug
656   | WayUser_a
657   | WayUser_b
658   | WayUser_c
659   | WayUser_d
660   | WayUser_e
661   | WayUser_f
662   | WayUser_g
663   | WayUser_h
664   | WayUser_i
665   | WayUser_j
666   | WayUser_k
667   | WayUser_l
668   | WayUser_m
669   | WayUser_n
670   | WayUser_o
671   | WayUser_A
672   | WayUser_B
673   deriving (Eq,Ord)
674
675 GLOBAL_VAR(v_Ways, [] ,[WayName])
676
677 allowed_combination way = way `elem` combs
678   where  -- the sub-lists must be ordered according to WayName, 
679          -- because findBuildTag sorts them
680     combs                = [ [WayProf, WayUnreg], 
681                              [WayProf, WaySMP]  ,
682                              [WayProf, WayNDP]  ]
683
684 findBuildTag :: IO [String]  -- new options
685 findBuildTag = do
686   way_names <- readIORef v_Ways
687   case sort way_names of
688      []  -> do  -- writeIORef v_Build_tag ""
689                 return []
690
691      [w] -> do let details = lkupWay w
692                writeIORef v_Build_tag (wayTag details)
693                return (wayOpts details)
694
695      ws  -> if not (allowed_combination ws)
696                 then throwDyn (CmdLineError $
697                                 "combination not supported: "  ++
698                                 foldr1 (\a b -> a ++ '/':b) 
699                                 (map (wayName . lkupWay) ws))
700                 else let stuff = map lkupWay ws
701                          tag   = concat (map wayTag stuff)
702                          flags = map wayOpts stuff
703                      in do
704                      writeIORef v_Build_tag tag
705                      return (concat flags)
706
707 lkupWay w = 
708    case lookup w way_details of
709         Nothing -> error "findBuildTag"
710         Just details -> details
711
712 data Way = Way {
713   wayTag   :: String,
714   wayName  :: String,
715   wayOpts  :: [String]
716   }
717
718 way_details :: [ (WayName, Way) ]
719 way_details =
720   [ (WayProf, Way  "p" "Profiling"  
721         [ "-fscc-profiling"
722         , "-DPROFILING"
723         , "-optc-DPROFILING"
724         , "-fvia-C" ]),
725
726     (WayTicky, Way  "t" "Ticky-ticky Profiling"  
727         [ "-fticky-ticky"
728         , "-DTICKY_TICKY"
729         , "-optc-DTICKY_TICKY"
730         , "-fvia-C" ]),
731
732     (WayUnreg, Way  "u" "Unregisterised" 
733         unregFlags ),
734
735     -- optl's below to tell linker where to find the PVM library -- HWL
736     (WayPar, Way  "mp" "Parallel" 
737         [ "-fparallel"
738         , "-D__PARALLEL_HASKELL__"
739         , "-optc-DPAR"
740         , "-package concurrent"
741         , "-optc-w"
742         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
743         , "-optl-lpvm3"
744         , "-optl-lgpvm3"
745         , "-fvia-C" ]),
746
747     -- at the moment we only change the RTS and could share compiler and libs!
748     (WayPar, Way  "mt" "Parallel ticky profiling" 
749         [ "-fparallel"
750         , "-D__PARALLEL_HASKELL__"
751         , "-optc-DPAR"
752         , "-optc-DPAR_TICKY"
753         , "-package concurrent"
754         , "-optc-w"
755         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
756         , "-optl-lpvm3"
757         , "-optl-lgpvm3"
758         , "-fvia-C" ]),
759
760     (WayPar, Way  "md" "Distributed" 
761         [ "-fparallel"
762         , "-D__PARALLEL_HASKELL__"
763         , "-D__DISTRIBUTED_HASKELL__"
764         , "-optc-DPAR"
765         , "-optc-DDIST"
766         , "-package concurrent"
767         , "-optc-w"
768         , "-optl-L${PVM_ROOT}/lib/${PVM_ARCH}"
769         , "-optl-lpvm3"
770         , "-optl-lgpvm3"
771         , "-fvia-C" ]),
772
773     (WayGran, Way  "mg" "GranSim" 
774         [ "-fgransim"
775         , "-D__GRANSIM__"
776         , "-optc-DGRAN"
777         , "-package concurrent"
778         , "-fvia-C" ]),
779
780     (WaySMP, Way  "s" "SMP"
781         [ "-fsmp"
782         , "-optc-pthread"
783 #ifndef freebsd_TARGET_OS
784         , "-optl-pthread"
785 #endif
786         , "-optc-DSMP"
787         , "-fvia-C" ]),
788
789     (WayNDP, Way  "ndp" "Nested data parallelism"
790         [ "-fparr"
791         , "-fflatten"]),
792
793     (WayUser_a,  Way  "a"  "User way 'a'"  ["$WAY_a_REAL_OPTS"]),       
794     (WayUser_b,  Way  "b"  "User way 'b'"  ["$WAY_b_REAL_OPTS"]),       
795     (WayUser_c,  Way  "c"  "User way 'c'"  ["$WAY_c_REAL_OPTS"]),       
796     (WayUser_d,  Way  "d"  "User way 'd'"  ["$WAY_d_REAL_OPTS"]),       
797     (WayUser_e,  Way  "e"  "User way 'e'"  ["$WAY_e_REAL_OPTS"]),       
798     (WayUser_f,  Way  "f"  "User way 'f'"  ["$WAY_f_REAL_OPTS"]),       
799     (WayUser_g,  Way  "g"  "User way 'g'"  ["$WAY_g_REAL_OPTS"]),       
800     (WayUser_h,  Way  "h"  "User way 'h'"  ["$WAY_h_REAL_OPTS"]),       
801     (WayUser_i,  Way  "i"  "User way 'i'"  ["$WAY_i_REAL_OPTS"]),       
802     (WayUser_j,  Way  "j"  "User way 'j'"  ["$WAY_j_REAL_OPTS"]),       
803     (WayUser_k,  Way  "k"  "User way 'k'"  ["$WAY_k_REAL_OPTS"]),       
804     (WayUser_l,  Way  "l"  "User way 'l'"  ["$WAY_l_REAL_OPTS"]),       
805     (WayUser_m,  Way  "m"  "User way 'm'"  ["$WAY_m_REAL_OPTS"]),       
806     (WayUser_n,  Way  "n"  "User way 'n'"  ["$WAY_n_REAL_OPTS"]),       
807     (WayUser_o,  Way  "o"  "User way 'o'"  ["$WAY_o_REAL_OPTS"]),       
808     (WayUser_A,  Way  "A"  "User way 'A'"  ["$WAY_A_REAL_OPTS"]),       
809     (WayUser_B,  Way  "B"  "User way 'B'"  ["$WAY_B_REAL_OPTS"]) 
810   ]
811
812 unregFlags = 
813    [ "-optc-DNO_REGS"
814    , "-optc-DUSE_MINIINTERPRETER"
815    , "-fno-asm-mangling"
816    , "-funregisterised"
817    , "-fvia-C" ]
818
819 -----------------------------------------------------------------------------
820 -- Options for particular phases
821
822 GLOBAL_VAR(v_Opt_dep,    [], [String])
823 GLOBAL_VAR(v_Anti_opt_C, [], [String])
824 GLOBAL_VAR(v_Opt_C,      [], [String])
825 GLOBAL_VAR(v_Opt_l,      [], [String])
826 GLOBAL_VAR(v_Opt_dll,    [], [String])
827
828 getStaticOpts :: IORef [String] -> IO [String]
829 getStaticOpts ref = readIORef ref >>= return . reverse