c70811b02bf4e5b0e88a9e3de2953b9eaddd3104
[ghc-hetmet.git] / ghc / compiler / main / DriverPipeline.hs
1 -----------------------------------------------------------------------------
2 --
3 -- GHC Driver
4 --
5 -- (c) The University of Glasgow 2005
6 --
7 -----------------------------------------------------------------------------
8
9 module DriverPipeline (
10         -- Run a series of compilation steps in a pipeline, for a
11         -- collection of source files.
12    oneShot, compileFile,
13
14         -- Interfaces for the batch-mode driver
15    staticLink,
16
17         -- Interfaces for the compilation manager (interpreted/batch-mode)
18    preprocess, 
19    compile, CompResult(..), 
20    link, 
21
22         -- DLL building
23    doMkDLL,
24
25   ) where
26
27 #include "HsVersions.h"
28
29 import Packages
30 import HeaderInfo
31 import DriverPhases
32 import SysTools         ( newTempName, addFilesToClean, getSysMan, copy )
33 import qualified SysTools       
34 import HscMain
35 import Finder
36 import HscTypes
37 import Outputable
38 import Module
39 import ErrUtils
40 import DynFlags
41 import StaticFlags      ( v_Ld_inputs, opt_Static, WayName(..) )
42 import Config
43 import Panic
44 import Util
45 import StringBuffer     ( hGetStringBuffer )
46 import BasicTypes       ( SuccessFlag(..) )
47 import Maybes           ( expectJust )
48 import Ctype            ( is_ident )
49 import StringBuffer     ( StringBuffer(..), lexemeToString )
50 import ParserCoreUtils  ( getCoreModuleName )
51 import SrcLoc           ( srcLocSpan, mkSrcLoc, unLoc )
52 import FastString       ( mkFastString )
53 import SrcLoc           ( Located(..) )
54
55 import Distribution.Compiler ( extensionsToGHCFlag )
56
57 import EXCEPTION
58 import DATA_IOREF       ( readIORef, writeIORef, IORef )
59 import GLAEXTS          ( Int(..) )
60
61 import Directory
62 import System
63 import IO
64 import Monad
65 import Data.List        ( isSuffixOf )
66 import Maybe
67
68
69 -- ---------------------------------------------------------------------------
70 -- Pre-process
71
72 -- Just preprocess a file, put the result in a temp. file (used by the
73 -- compilation manager during the summary phase).
74 --
75 -- We return the augmented DynFlags, because they contain the result
76 -- of slurping in the OPTIONS pragmas
77
78 preprocess :: DynFlags -> (FilePath, Maybe Phase) -> IO (DynFlags, FilePath)
79 preprocess dflags (filename, mb_phase) =
80   ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename) 
81   runPipeline anyHsc dflags (filename, mb_phase) Temporary Nothing{-no ModLocation-}
82
83 -- ---------------------------------------------------------------------------
84 -- Compile
85
86 -- Compile a single module, under the control of the compilation manager.
87 --
88 -- This is the interface between the compilation manager and the
89 -- compiler proper (hsc), where we deal with tedious details like
90 -- reading the OPTIONS pragma from the source file, and passing the
91 -- output of hsc through the C compiler.
92
93 -- NB.  No old interface can also mean that the source has changed.
94
95 compile :: HscEnv
96         -> ModSummary
97         -> Maybe Linkable       -- Just linkable <=> source unchanged
98         -> Maybe ModIface       -- Old interface, if available
99         -> Int -> Int
100         -> IO CompResult
101
102 data CompResult
103    = CompOK   ModDetails        -- New details
104               ModIface          -- New iface
105               (Maybe Linkable)  -- a Maybe, for the same reasons as hm_linkable
106
107    | CompErrs 
108
109
110 compile hsc_env mod_summary maybe_old_linkable old_iface mod_index nmods = do 
111
112    let dflags0     = ms_hspp_opts mod_summary
113        this_mod    = ms_mod mod_summary
114        src_flavour = ms_hsc_src mod_summary
115
116        have_object 
117                | Just l <- maybe_old_linkable, isObjectLinkable l = True
118                | otherwise = False
119
120    showPass dflags0 ("Compiling " ++ showModMsg have_object mod_summary)
121
122    let location   = ms_location mod_summary
123    let input_fn   = expectJust "compile:hs" (ml_hs_file location) 
124    let input_fnpp = ms_hspp_file mod_summary
125
126    debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
127
128    let (basename, _) = splitFilename input_fn
129
130   -- We add the directory in which the .hs files resides) to the import path.
131   -- This is needed when we try to compile the .hc file later, if it
132   -- imports a _stub.h file that we created here.
133    let current_dir = directoryOf basename
134        old_paths   = includePaths dflags0
135        dflags      = dflags0 { includePaths = current_dir : old_paths }
136
137    -- Figure out what lang we're generating
138    let hsc_lang = hscMaybeAdjustTarget dflags StopLn src_flavour (hscTarget dflags)
139    -- ... and what the next phase should be
140    let next_phase = hscNextPhase dflags src_flavour hsc_lang
141    -- ... and what file to generate the output into
142    output_fn <- getOutputFilename dflags next_phase 
143                         Temporary basename next_phase (Just location)
144
145    let dflags' = dflags { hscTarget = hsc_lang,
146                                 hscOutName = output_fn,
147                                 extCoreName = basename ++ ".hcr" }
148
149    -- -no-recomp should also work with --make
150    let do_recomp = dopt Opt_RecompChecking dflags
151        source_unchanged = isJust maybe_old_linkable && do_recomp
152        hsc_env' = hsc_env { hsc_dflags = dflags' }
153        object_filename = ml_obj_file location
154
155    let getStubLinkable False = return []
156        getStubLinkable True
157            = do stub_o <- compileStub dflags' this_mod location
158                 return [ DotO stub_o ]
159
160        handleBatch (HscNoRecomp, iface, details)
161            = ASSERT (isJust maybe_old_linkable)
162              return (CompOK details iface maybe_old_linkable)
163        handleBatch (HscRecomp hasStub, iface, details)
164            | isHsBoot src_flavour
165                = return (CompOK details iface Nothing)
166            | otherwise
167                = do stub_unlinked <- getStubLinkable hasStub
168                     (hs_unlinked, unlinked_time) <-
169                         case hsc_lang of
170                           HscNothing
171                             -> return ([], ms_hs_date mod_summary)
172                           -- We're in --make mode: finish the compilation pipeline.
173                           _other
174                             -> do runPipeline StopLn dflags (output_fn,Nothing) Persistent
175                                               (Just location)
176                                   -- The object filename comes from the ModLocation
177                                   o_time <- getModificationTime object_filename
178                                   return ([DotO object_filename], o_time)
179                     let linkable = LM unlinked_time this_mod
180                                    (hs_unlinked ++ stub_unlinked)
181                     return (CompOK details iface (Just linkable))
182
183        handleInterpreted (InteractiveNoRecomp, iface, details)
184            = ASSERT (isJust maybe_old_linkable)
185              return (CompOK details iface maybe_old_linkable)
186        handleInterpreted (InteractiveRecomp hasStub comp_bc, iface, details)
187            = do stub_unlinked <- getStubLinkable hasStub
188                 let hs_unlinked = [BCOs comp_bc]
189                     unlinked_time = ms_hs_date mod_summary
190                   -- Why do we use the timestamp of the source file here,
191                   -- rather than the current time?  This works better in
192                   -- the case where the local clock is out of sync
193                   -- with the filesystem's clock.  It's just as accurate:
194                   -- if the source is modified, then the linkable will
195                   -- be out of date.
196                 let linkable = LM unlinked_time this_mod
197                                (hs_unlinked ++ stub_unlinked)
198                 return (CompOK details iface (Just linkable))
199
200    let runCompiler compiler handle
201            = do mbResult <- compiler hsc_env' mod_summary
202                                      source_unchanged old_iface
203                                      (Just (mod_index, nmods))
204                 case mbResult of
205                   Nothing     -> return CompErrs
206                   Just result -> handle result
207    -- run the compiler
208    case hsc_lang of
209      HscInterpreted | not (isHsBoot src_flavour) -- We can't compile boot files to
210                                                  -- bytecode so don't even try.
211          -> runCompiler hscCompileInteractive handleInterpreted
212      HscNothing
213          -> runCompiler hscCompileNothing handleBatch
214      _other
215          -> runCompiler hscCompileBatch handleBatch
216
217 -----------------------------------------------------------------------------
218 -- stub .h and .c files (for foreign export support)
219
220 -- The _stub.c file is derived from the haskell source file, possibly taking
221 -- into account the -stubdir option.
222 --
223 -- Consequently, we derive the _stub.o filename from the haskell object
224 -- filename.  
225 --
226 -- This isn't necessarily the same as the object filename we
227 -- would get if we just compiled the _stub.c file using the pipeline.
228 -- For example:
229 --
230 --    ghc src/A.hs -odir obj
231 -- 
232 -- results in obj/A.o, and src/A_stub.c.  If we compile src/A_stub.c with
233 -- -odir obj, we would get obj/src/A_stub.o, which is wrong; we want
234 -- obj/A_stub.o.
235
236 compileStub :: DynFlags -> Module -> ModLocation -> IO FilePath
237 compileStub dflags mod location = do
238         let (o_base, o_ext) = splitFilename (ml_obj_file location)
239             stub_o = o_base ++ "_stub" `joinFileExt` o_ext
240
241         -- compile the _stub.c file w/ gcc
242         let (stub_c,_) = mkStubPaths dflags mod location
243         runPipeline StopLn dflags (stub_c,Nothing) 
244                 (SpecificFile stub_o) Nothing{-no ModLocation-}
245
246         return stub_o
247
248
249 -- ---------------------------------------------------------------------------
250 -- Link
251
252 link :: GhcMode                 -- interactive or batch
253      -> DynFlags                -- dynamic flags
254      -> Bool                    -- attempt linking in batch mode?
255      -> HomePackageTable        -- what to link
256      -> IO SuccessFlag
257
258 -- For the moment, in the batch linker, we don't bother to tell doLink
259 -- which packages to link -- it just tries all that are available.
260 -- batch_attempt_linking should only be *looked at* in batch mode.  It
261 -- should only be True if the upsweep was successful and someone
262 -- exports main, i.e., we have good reason to believe that linking
263 -- will succeed.
264
265 #ifdef GHCI
266 link Interactive dflags batch_attempt_linking hpt
267     = do -- Not Linking...(demand linker will do the job)
268          return Succeeded
269 #endif
270
271 link JustTypecheck dflags batch_attempt_linking hpt
272    = return Succeeded
273
274 link BatchCompile dflags batch_attempt_linking hpt
275    | batch_attempt_linking
276    = do 
277         let 
278             home_mod_infos = moduleEnvElts hpt
279
280             -- the packages we depend on
281             pkg_deps  = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
282
283             -- the linkables to link
284             linkables = map (expectJust "link".hm_linkable) home_mod_infos
285
286         debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
287
288         -- check for the -no-link flag
289         if isNoLink (ghcLink dflags)
290           then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
291                   return Succeeded
292           else do
293
294         let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
295             obj_files = concatMap getOfiles linkables
296
297             exe_file = exeFileName dflags
298
299         -- if the modification time on the executable is later than the
300         -- modification times on all of the objects, then omit linking
301         -- (unless the -no-recomp flag was given).
302         e_exe_time <- IO.try $ getModificationTime exe_file
303         let linking_needed 
304                 | Left _  <- e_exe_time = True
305                 | Right t <- e_exe_time = 
306                         any (t <) (map linkableTime linkables)
307
308         if dopt Opt_RecompChecking dflags && not linking_needed
309            then do debugTraceMsg dflags 1 (text exe_file <+> ptext SLIT("is up to date, linking not required."))
310                    return Succeeded
311            else do
312
313         debugTraceMsg dflags 1 (ptext SLIT("Linking") <+> text exe_file
314                                  <+> text "...")
315
316         -- Don't showPass in Batch mode; doLink will do that for us.
317         let link = case ghcLink dflags of
318                 MkDLL       -> doMkDLL
319                 StaticLink  -> staticLink
320         link dflags obj_files pkg_deps
321
322         debugTraceMsg dflags 3 (text "link: done")
323
324         -- staticLink only returns if it succeeds
325         return Succeeded
326
327    | otherwise
328    = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
329                                 text "   Main.main not exported; not linking.")
330         return Succeeded
331       
332
333 -- -----------------------------------------------------------------------------
334 -- Compile files in one-shot mode.
335
336 oneShot :: DynFlags -> Phase -> [(String, Maybe Phase)] -> IO ()
337 oneShot dflags stop_phase srcs = do
338   o_files <- mapM (compileFile dflags stop_phase) srcs
339   doLink dflags stop_phase o_files
340
341 compileFile :: DynFlags -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
342 compileFile dflags stop_phase (src, mb_phase) = do
343    exists <- doesFileExist src
344    when (not exists) $ 
345         throwDyn (CmdLineError ("does not exist: " ++ src))
346    
347    let
348         split     = dopt Opt_SplitObjs dflags
349         mb_o_file = outputFile dflags
350         ghc_link  = ghcLink dflags      -- Set by -c or -no-link
351
352         -- When linking, the -o argument refers to the linker's output. 
353         -- otherwise, we use it as the name for the pipeline's output.
354         output
355          | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
356                 -- -o foo applies to linker
357          | Just o_file <- mb_o_file = SpecificFile o_file
358                 -- -o foo applies to the file we are compiling now
359          | otherwise = Persistent
360
361         stop_phase' = case stop_phase of 
362                         As | split -> SplitAs
363                         other      -> stop_phase
364
365    (_, out_file) <- runPipeline stop_phase' dflags
366                           (src, mb_phase) output Nothing{-no ModLocation-}
367    return out_file
368
369
370 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
371 doLink dflags stop_phase o_files
372   | not (isStopLn stop_phase)
373   = return ()           -- We stopped before the linking phase
374
375   | otherwise
376   = case ghcLink dflags of
377         NoLink     -> return ()
378         StaticLink -> staticLink dflags o_files link_pkgs
379         MkDLL      -> doMkDLL dflags o_files link_pkgs
380   where
381    -- Always link in the haskell98 package for static linking.  Other
382    -- packages have to be specified via the -package flag.
383     link_pkgs
384           | ExtPackage h98_id <- haskell98PackageId (pkgState dflags) = [h98_id]
385           | otherwise = []
386
387
388 -- ---------------------------------------------------------------------------
389 -- Run a compilation pipeline, consisting of multiple phases.
390
391 -- This is the interface to the compilation pipeline, which runs
392 -- a series of compilation steps on a single source file, specifying
393 -- at which stage to stop.
394
395 -- The DynFlags can be modified by phases in the pipeline (eg. by
396 -- GHC_OPTIONS pragmas), and the changes affect later phases in the
397 -- pipeline.
398
399 data PipelineOutput 
400   = Temporary
401         -- output should be to a temporary file: we're going to
402         -- run more compilation steps on this output later
403   | Persistent
404         -- we want a persistent file, i.e. a file in the current directory
405         -- derived from the input filename, but with the appropriate extension.
406         -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
407   | SpecificFile FilePath
408         -- the output must go into the specified file.
409
410 runPipeline
411   :: Phase                      -- When to stop
412   -> DynFlags                   -- Dynamic flags
413   -> (FilePath,Maybe Phase)     -- Input filename (and maybe -x suffix)
414   -> PipelineOutput             -- Output filename
415   -> Maybe ModLocation          -- A ModLocation, if this is a Haskell module
416   -> IO (DynFlags, FilePath)    -- (final flags, output filename)
417
418 runPipeline stop_phase dflags (input_fn, mb_phase) output maybe_loc
419   = do
420   let (basename, suffix) = splitFilename input_fn
421
422         -- If we were given a -x flag, then use that phase to start from
423       start_phase
424         | Just x_phase <- mb_phase = x_phase
425         | otherwise                = startPhase suffix
426
427   -- We want to catch cases of "you can't get there from here" before
428   -- we start the pipeline, because otherwise it will just run off the
429   -- end.
430   --
431   -- There is a partial ordering on phases, where A < B iff A occurs
432   -- before B in a normal compilation pipeline.
433
434   when (not (start_phase `happensBefore` stop_phase)) $
435         throwDyn (UsageError 
436                     ("cannot compile this file to desired target: "
437                        ++ input_fn))
438
439   -- this is a function which will be used to calculate output file names
440   -- as we go along (we partially apply it to some of its inputs here)
441   let get_output_fn = getOutputFilename dflags stop_phase output basename
442
443   -- Execute the pipeline...
444   (dflags', output_fn, maybe_loc) <- 
445         pipeLoop dflags start_phase stop_phase input_fn 
446                  basename suffix get_output_fn maybe_loc
447
448   -- Sometimes, a compilation phase doesn't actually generate any output
449   -- (eg. the CPP phase when -fcpp is not turned on).  If we end on this
450   -- stage, but we wanted to keep the output, then we have to explicitly
451   -- copy the file.
452   case output of
453     Temporary -> 
454         return (dflags', output_fn)
455     _other ->
456         do final_fn <- get_output_fn stop_phase maybe_loc
457            when (final_fn /= output_fn) $
458                   copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
459                         ++ "'") output_fn final_fn
460            return (dflags', final_fn)
461                 
462
463
464 pipeLoop :: DynFlags -> Phase -> Phase 
465          -> FilePath  -> String -> Suffix
466          -> (Phase -> Maybe ModLocation -> IO FilePath)
467          -> Maybe ModLocation
468          -> IO (DynFlags, FilePath, Maybe ModLocation)
469
470 pipeLoop dflags phase stop_phase 
471          input_fn orig_basename orig_suff 
472          orig_get_output_fn maybe_loc
473
474   | phase `eqPhase` stop_phase            -- All done
475   = return (dflags, input_fn, maybe_loc)
476
477   | not (phase `happensBefore` stop_phase)
478         -- Something has gone wrong.  We'll try to cover all the cases when
479         -- this could happen, so if we reach here it is a panic.
480         -- eg. it might happen if the -C flag is used on a source file that
481         -- has {-# OPTIONS -fasm #-}.
482   = panic ("pipeLoop: at phase " ++ show phase ++ 
483            " but I wanted to stop at phase " ++ show stop_phase)
484
485   | otherwise 
486   = do  { (next_phase, dflags', maybe_loc, output_fn)
487                 <- runPhase phase stop_phase dflags orig_basename 
488                             orig_suff input_fn orig_get_output_fn maybe_loc
489         ; pipeLoop dflags' next_phase stop_phase output_fn
490                    orig_basename orig_suff orig_get_output_fn maybe_loc }
491
492 getOutputFilename
493   :: DynFlags -> Phase -> PipelineOutput -> String
494   -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
495 getOutputFilename dflags stop_phase output basename
496  = func
497  where
498         hcsuf      = hcSuf dflags
499         odir       = objectDir dflags
500         osuf       = objectSuf dflags
501         keep_hc    = dopt Opt_KeepHcFiles dflags
502         keep_raw_s = dopt Opt_KeepRawSFiles dflags
503         keep_s     = dopt Opt_KeepSFiles dflags
504
505         myPhaseInputExt HCc    = hcsuf
506         myPhaseInputExt StopLn = osuf
507         myPhaseInputExt other  = phaseInputExt other
508
509         func next_phase maybe_location
510            | is_last_phase, Persistent <- output     = persistent_fn
511            | is_last_phase, SpecificFile f <- output = return f
512            | keep_this_output                        = persistent_fn
513            | otherwise                               = newTempName dflags suffix
514            where
515                 is_last_phase = next_phase `eqPhase` stop_phase
516
517                 -- sometimes, we keep output from intermediate stages
518                 keep_this_output = 
519                      case next_phase of
520                              StopLn              -> True
521                              Mangle | keep_raw_s -> True
522                              As     | keep_s     -> True
523                              HCc    | keep_hc    -> True
524                              _other              -> False
525
526                 suffix = myPhaseInputExt next_phase
527
528                 -- persistent object files get put in odir
529                 persistent_fn 
530                    | StopLn <- next_phase = return odir_persistent
531                    | otherwise            = return persistent
532
533                 persistent = basename `joinFileExt` suffix
534
535                 odir_persistent
536                    | Just loc <- maybe_location = ml_obj_file loc
537                    | Just d <- odir = d `joinFileName` persistent
538                    | otherwise      = persistent
539
540
541 -- -----------------------------------------------------------------------------
542 -- Each phase in the pipeline returns the next phase to execute, and the
543 -- name of the file in which the output was placed.
544 --
545 -- We must do things dynamically this way, because we often don't know
546 -- what the rest of the phases will be until part-way through the
547 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
548 -- of a source file can change the latter stages of the pipeline from
549 -- taking the via-C route to using the native code generator.
550
551 runPhase :: Phase       -- Do this phase first
552          -> Phase       -- Stop just before this phase
553          -> DynFlags
554          -> String      -- basename of original input source
555          -> String      -- its extension
556          -> FilePath    -- name of file which contains the input to this phase.
557          -> (Phase -> Maybe ModLocation -> IO FilePath)
558                         -- how to calculate the output filename
559          -> Maybe ModLocation           -- the ModLocation, if we have one
560          -> IO (Phase,                  -- next phase
561                 DynFlags,               -- new dynamic flags
562                 Maybe ModLocation,      -- the ModLocation, if we have one
563                 FilePath)               -- output filename
564
565         -- Invariant: the output filename always contains the output
566         -- Interesting case: Hsc when there is no recompilation to do
567         --                   Then the output filename is still a .o file 
568
569 -------------------------------------------------------------------------------
570 -- Unlit phase 
571
572 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
573   = do let unlit_flags = getOpts dflags opt_L
574        -- The -h option passes the file name for unlit to put in a #line directive
575        output_fn <- get_output_fn (Cpp sf) maybe_loc
576
577        SysTools.runUnlit dflags 
578                 (map SysTools.Option unlit_flags ++
579                           [ SysTools.Option     "-h"
580                           , SysTools.Option     input_fn
581                           , SysTools.FileOption "" input_fn
582                           , SysTools.FileOption "" output_fn
583                           ])
584
585        return (Cpp sf, dflags, maybe_loc, output_fn)
586
587 -------------------------------------------------------------------------------
588 -- Cpp phase : (a) gets OPTIONS out of file
589 --             (b) runs cpp if necessary
590
591 runPhase (Cpp sf) _stop dflags0 basename suff input_fn get_output_fn maybe_loc
592   = do src_opts <- getOptionsFromFile input_fn
593        (dflags,unhandled_flags) <- parseDynamicFlags dflags0 (map unLoc src_opts)
594        checkProcessArgsResult unhandled_flags (basename `joinFileExt` suff)
595
596        if not (dopt Opt_Cpp dflags) then
597            -- no need to preprocess CPP, just pass input file along
598            -- to the next phase of the pipeline.
599           return (HsPp sf, dflags, maybe_loc, input_fn)
600         else do
601             output_fn <- get_output_fn (HsPp sf) maybe_loc
602             doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
603             return (HsPp sf, dflags, maybe_loc, output_fn)
604
605 -------------------------------------------------------------------------------
606 -- HsPp phase 
607
608 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
609   = do if not (dopt Opt_Pp dflags) then
610            -- no need to preprocess, just pass input file along
611            -- to the next phase of the pipeline.
612           return (Hsc sf, dflags, maybe_loc, input_fn)
613         else do
614             let hspp_opts = getOpts dflags opt_F
615             let orig_fn = basename `joinFileExt` suff
616             output_fn <- get_output_fn (Hsc sf) maybe_loc
617             SysTools.runPp dflags
618                            ( [ SysTools.Option     orig_fn
619                              , SysTools.Option     input_fn
620                              , SysTools.FileOption "" output_fn
621                              ] ++
622                              map SysTools.Option hspp_opts
623                            )
624             return (Hsc sf, dflags, maybe_loc, output_fn)
625
626 -----------------------------------------------------------------------------
627 -- Hsc phase
628
629 -- Compilation of a single module, in "legacy" mode (_not_ under
630 -- the direction of the compilation manager).
631 runPhase (Hsc src_flavour) stop dflags0 basename suff input_fn get_output_fn _maybe_loc 
632  = do   -- normal Hsc mode, not mkdependHS
633
634   -- we add the current directory (i.e. the directory in which
635   -- the .hs files resides) to the import path, since this is
636   -- what gcc does, and it's probably what you want.
637         let current_dir = directoryOf basename
638         
639             paths = includePaths dflags0
640             dflags = dflags0 { includePaths = current_dir : paths }
641         
642   -- gather the imports and module name
643         (hspp_buf,mod_name) <- 
644             case src_flavour of
645                 ExtCoreFile -> do {  -- no explicit imports in ExtCore input.
646                                   ; m <- getCoreModuleName input_fn
647                                   ; return (Nothing, mkModule m) }
648
649                 other -> do { buf <- hGetStringBuffer input_fn
650                             ; (_,_,L _ mod_name) <- getImports dflags buf input_fn
651                             ; return (Just buf, mod_name) }
652
653   -- Build a ModLocation to pass to hscMain.
654   -- The source filename is rather irrelevant by now, but it's used
655   -- by hscMain for messages.  hscMain also needs 
656   -- the .hi and .o filenames, and this is as good a way
657   -- as any to generate them, and better than most. (e.g. takes 
658   -- into accout the -osuf flags)
659         location1 <- mkHomeModLocation2 dflags mod_name basename suff
660
661   -- Boot-ify it if necessary
662         let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
663                       | otherwise            = location1 
664                                         
665
666   -- Take -ohi into account if present
667   -- This can't be done in mkHomeModuleLocation because
668   -- it only applies to the module being compiles
669         let ohi = outputHi dflags
670             location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
671                       | otherwise      = location2
672
673   -- Take -o into account if present
674   -- Very like -ohi, but we must *only* do this if we aren't linking
675   -- (If we're linking then the -o applies to the linked thing, not to
676   -- the object file for one module.)
677   -- Note the nasty duplication with the same computation in compileFile above
678         let expl_o_file = outputFile dflags
679             location4 | Just ofile <- expl_o_file
680                       , isNoLink (ghcLink dflags)
681                       = location3 { ml_obj_file = ofile }
682                       | otherwise = location3
683
684   -- Make the ModSummary to hand to hscMain
685         src_timestamp <- getModificationTime (basename `joinFileExt` suff)
686         let
687             unused_field = panic "runPhase:ModSummary field"
688                 -- Some fields are not looked at by hscMain
689             mod_summary = ModSummary {  ms_mod       = mod_name, 
690                                         ms_hsc_src   = src_flavour,
691                                         ms_hspp_file = input_fn,
692                                         ms_hspp_opts = dflags,
693                                         ms_hspp_buf  = hspp_buf,
694                                         ms_location  = location4,
695                                         ms_hs_date   = src_timestamp,
696                                         ms_obj_date  = Nothing,
697                                         ms_imps      = unused_field,
698                                         ms_srcimps   = unused_field }
699
700             o_file = ml_obj_file location4      -- The real object file
701
702
703   -- Figure out if the source has changed, for recompilation avoidance.
704   --
705   -- Setting source_unchanged to True means that M.o seems
706   -- to be up to date wrt M.hs; so no need to recompile unless imports have
707   -- changed (which the compiler itself figures out).
708   -- Setting source_unchanged to False tells the compiler that M.o is out of
709   -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
710         let do_recomp = dopt Opt_RecompChecking dflags
711         source_unchanged <- 
712           if not do_recomp || not (isStopLn stop)
713                 -- Set source_unchanged to False unconditionally if
714                 --      (a) recompilation checker is off, or
715                 --      (b) we aren't going all the way to .o file (e.g. ghc -S)
716              then return False  
717                 -- Otherwise look at file modification dates
718              else do o_file_exists <- doesFileExist o_file
719                      if not o_file_exists
720                         then return False       -- Need to recompile
721                         else do t2 <- getModificationTime o_file
722                                 if t2 > src_timestamp
723                                   then return True
724                                   else return False
725
726   -- get the DynFlags
727         let hsc_lang = hscMaybeAdjustTarget dflags stop src_flavour (hscTarget dflags)
728         let next_phase = hscNextPhase dflags src_flavour hsc_lang
729         output_fn  <- get_output_fn next_phase (Just location4)
730
731         let dflags' = dflags { hscTarget = hsc_lang,
732                                hscOutName = output_fn,
733                                extCoreName = basename ++ ".hcr" }
734
735         hsc_env <- newHscEnv dflags'
736
737   -- Tell the finder cache about this module
738         addHomeModuleToFinder hsc_env mod_name location4
739
740   -- run the compiler!
741         mbResult <- hscCompileOneShot hsc_env
742                           mod_summary source_unchanged 
743                           Nothing       -- No iface
744                           Nothing       -- No "module i of n" progress info
745
746         case mbResult of
747           Nothing -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
748           Just HscNoRecomp
749               -> do SysTools.touch dflags' "Touching object file" o_file
750                     -- The .o file must have a later modification date
751                     -- than the source file (else we wouldn't be in HscNoRecomp)
752                     -- but we touch it anyway, to keep 'make' happy (we think).
753                     return (StopLn, dflags', Just location4, o_file)
754           Just (HscRecomp hasStub)
755               -> do when hasStub $
756                          do stub_o <- compileStub dflags' mod_name location4
757                             consIORef v_Ld_inputs stub_o
758                     -- In the case of hs-boot files, generate a dummy .o-boot 
759                     -- stamp file for the benefit of Make
760                     when (isHsBoot src_flavour) $
761                       SysTools.touch dflags' "Touching object file" o_file
762                     return (next_phase, dflags', Just location4, output_fn)
763
764 -----------------------------------------------------------------------------
765 -- Cmm phase
766
767 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
768   = do
769        output_fn <- get_output_fn Cmm maybe_loc
770        doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn 
771        return (Cmm, dflags, maybe_loc, output_fn)
772
773 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
774   = do
775         let hsc_lang = hscMaybeAdjustTarget dflags stop HsSrcFile (hscTarget dflags)
776         let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
777         output_fn <- get_output_fn next_phase maybe_loc
778
779         let dflags' = dflags { hscTarget = hsc_lang,
780                                hscOutName = output_fn,
781                                extCoreName = basename ++ ".hcr" }
782
783         ok <- hscCmmFile dflags' input_fn
784
785         when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
786
787         return (next_phase, dflags, maybe_loc, output_fn)
788
789 -----------------------------------------------------------------------------
790 -- Cc phase
791
792 -- we don't support preprocessing .c files (with -E) now.  Doing so introduces
793 -- way too many hacks, and I can't say I've ever used it anyway.
794
795 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
796    | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
797    = do let cc_opts = getOpts dflags opt_c
798             hcc = cc_phase `eqPhase` HCc
799
800         let cmdline_include_paths = includePaths dflags
801
802         -- HC files have the dependent packages stamped into them
803         pkgs <- if hcc then getHCFilePackages input_fn else return []
804
805         -- add package include paths even if we're just compiling .c
806         -- files; this is the Value Add(TM) that using ghc instead of
807         -- gcc gives you :)
808         pkg_include_dirs <- getPackageIncludePath dflags pkgs
809         let include_paths = foldr (\ x xs -> "-I" : x : xs) []
810                               (cmdline_include_paths ++ pkg_include_dirs)
811
812         let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
813         let pic_c_flags = picCCOpts dflags
814
815         let verb = getVerbFlag dflags
816
817         pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
818
819         let split_objs = dopt Opt_SplitObjs dflags
820             split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
821                       | otherwise         = [ ]
822
823         let excessPrecision = dopt Opt_ExcessPrecision dflags
824
825         let cc_opt | optLevel dflags >= 2 = "-O2"
826                    | otherwise            = "-O"
827
828         -- Decide next phase
829         
830         let mangle = dopt Opt_DoAsmMangling dflags
831             next_phase
832                 | hcc && mangle     = Mangle
833                 | otherwise         = As
834         output_fn <- get_output_fn next_phase maybe_loc
835
836         let
837           more_hcc_opts =
838 #if i386_TARGET_ARCH
839                 -- on x86 the floating point regs have greater precision
840                 -- than a double, which leads to unpredictable results.
841                 -- By default, we turn this off with -ffloat-store unless
842                 -- the user specified -fexcess-precision.
843                 (if excessPrecision then [] else [ "-ffloat-store" ]) ++
844 #endif
845                 -- gcc's -fstrict-aliasing allows two accesses to memory
846                 -- to be considered non-aliasing if they have different types.
847                 -- This interacts badly with the C code we generate, which is
848                 -- very weakly typed, being derived from C--.
849                 ["-fno-strict-aliasing"]
850
851
852
853         SysTools.runCc dflags (
854                 -- force the C compiler to interpret this file as C when
855                 -- compiling .hc files, by adding the -x c option.
856                 -- Also useful for plain .c files, just in case GHC saw a 
857                 -- -x c option.
858                         [ SysTools.Option "-x", SysTools.Option "c"] ++
859                         [ SysTools.FileOption "" input_fn
860                         , SysTools.Option "-o"
861                         , SysTools.FileOption "" output_fn
862                         ]
863                        ++ map SysTools.Option (
864                           md_c_flags
865                        ++ pic_c_flags
866                        ++ (if hcc && mangle
867                              then md_regd_c_flags
868                              else [])
869                        ++ (if hcc 
870                              then more_hcc_opts
871                              else [])
872                        ++ [ verb, "-S", "-Wimplicit", cc_opt ]
873                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
874                        ++ cc_opts
875                        ++ split_opt
876                        ++ include_paths
877                        ++ pkg_extra_cc_opts
878                        ))
879
880         return (next_phase, dflags, maybe_loc, output_fn)
881
882         -- ToDo: postprocess the output from gcc
883
884 -----------------------------------------------------------------------------
885 -- Mangle phase
886
887 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
888    = do let mangler_opts = getOpts dflags opt_m
889
890 #if i386_TARGET_ARCH
891         machdep_opts <- return [ show (stolen_x86_regs dflags) ]
892 #else
893         machdep_opts <- return []
894 #endif
895
896         let split = dopt Opt_SplitObjs dflags
897             next_phase
898                 | split = SplitMangle
899                 | otherwise = As
900         output_fn <- get_output_fn next_phase maybe_loc
901
902         SysTools.runMangle dflags (map SysTools.Option mangler_opts
903                           ++ [ SysTools.FileOption "" input_fn
904                              , SysTools.FileOption "" output_fn
905                              ]
906                           ++ map SysTools.Option machdep_opts)
907
908         return (next_phase, dflags, maybe_loc, output_fn)
909
910 -----------------------------------------------------------------------------
911 -- Splitting phase
912
913 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
914   = do  -- tmp_pfx is the prefix used for the split .s files
915         -- We also use it as the file to contain the no. of split .s files (sigh)
916         split_s_prefix <- SysTools.newTempName dflags "split"
917         let n_files_fn = split_s_prefix
918
919         SysTools.runSplit dflags
920                           [ SysTools.FileOption "" input_fn
921                           , SysTools.FileOption "" split_s_prefix
922                           , SysTools.FileOption "" n_files_fn
923                           ]
924
925         -- Save the number of split files for future references
926         s <- readFile n_files_fn
927         let n_files = read s :: Int
928         writeIORef v_Split_info (split_s_prefix, n_files)
929
930         -- Remember to delete all these files
931         addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
932                         | n <- [1..n_files]]
933
934         return (SplitAs, dflags, maybe_loc, "**splitmangle**")
935           -- we don't use the filename
936
937 -----------------------------------------------------------------------------
938 -- As phase
939
940 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
941   = do  let as_opts =  getOpts dflags opt_a
942         let cmdline_include_paths = includePaths dflags
943
944         output_fn <- get_output_fn StopLn maybe_loc
945
946         -- we create directories for the object file, because it
947         -- might be a hierarchical module.
948         createDirectoryHierarchy (directoryOf output_fn)
949
950         SysTools.runAs dflags   
951                        (map SysTools.Option as_opts
952                        ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
953                        ++ [ SysTools.Option "-c"
954                           , SysTools.FileOption "" input_fn
955                           , SysTools.Option "-o"
956                           , SysTools.FileOption "" output_fn
957                           ])
958
959         return (StopLn, dflags, maybe_loc, output_fn)
960
961
962 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
963   = do  
964         output_fn <- get_output_fn StopLn maybe_loc
965
966         let (base_o, _) = splitFilename output_fn
967             split_odir  = base_o ++ "_split"
968             osuf = objectSuf dflags
969
970         createDirectoryHierarchy split_odir
971
972         -- remove M_split/ *.o, because we're going to archive M_split/ *.o
973         -- later and we don't want to pick up any old objects.
974         fs <- getDirectoryContents split_odir 
975         mapM_ removeFile $ map (split_odir `joinFileName`)
976                          $ filter (osuf `isSuffixOf`) fs
977
978         let as_opts = getOpts dflags opt_a
979
980         (split_s_prefix, n) <- readIORef v_Split_info
981
982         let split_s   n = split_s_prefix ++ "__" ++ show n `joinFileExt` "s"
983             split_obj n = split_odir `joinFileName`
984                                 filenameOf base_o ++ "__" ++ show n
985                                         `joinFileExt` osuf
986
987         let assemble_file n
988               = SysTools.runAs dflags
989                          (map SysTools.Option as_opts ++
990                          [ SysTools.Option "-c"
991                          , SysTools.Option "-o"
992                          , SysTools.FileOption "" (split_obj n)
993                          , SysTools.FileOption "" (split_s n)
994                          ])
995         
996         mapM_ assemble_file [1..n]
997
998         -- and join the split objects into a single object file:
999         let ld_r args = SysTools.runLink dflags ([ 
1000                                 SysTools.Option "-nostdlib",
1001                                 SysTools.Option "-nodefaultlibs",
1002                                 SysTools.Option "-Wl,-r", 
1003                                 SysTools.Option ld_x_flag, 
1004                                 SysTools.Option "-o", 
1005                                 SysTools.FileOption "" output_fn ] ++ args)
1006             ld_x_flag | null cLD_X = ""
1007                       | otherwise  = "-Wl,-x"     
1008
1009         if cLdIsGNULd == "YES"
1010             then do 
1011                   let script = split_odir `joinFileName` "ld.script"
1012                   writeFile script $
1013                       "INPUT(" ++ unwords (map split_obj [1..n]) ++ ")"
1014                   ld_r [SysTools.FileOption "" script]
1015             else do
1016                   ld_r (map (SysTools.FileOption "" . split_obj) [1..n])
1017
1018         return (StopLn, dflags, maybe_loc, output_fn)
1019
1020
1021 -----------------------------------------------------------------------------
1022 -- MoveBinary sort-of-phase
1023 -- After having produced a binary, move it somewhere else and generate a
1024 -- wrapper script calling the binary. Currently, we need this only in 
1025 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1026 -- central directory.
1027 -- This is called from staticLink below, after linking. I haven't made it
1028 -- a separate phase to minimise interfering with other modules, and
1029 -- we don't need the generality of a phase (MoveBinary is always
1030 -- done after linking and makes only sense in a parallel setup)   -- HWL
1031
1032 runPhase_MoveBinary input_fn
1033   = do  
1034         sysMan   <- getSysMan
1035         pvm_root <- getEnv "PVM_ROOT"
1036         pvm_arch <- getEnv "PVM_ARCH"
1037         let 
1038            pvm_executable_base = "=" ++ input_fn
1039            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1040         -- nuke old binary; maybe use configur'ed names for cp and rm?
1041         system ("rm -f " ++ pvm_executable)
1042         -- move the newly created binary into PVM land
1043         system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
1044         -- generate a wrapper script for running a parallel prg under PVM
1045         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1046         return True
1047
1048 -- generates a Perl skript starting a parallel prg under PVM
1049 mk_pvm_wrapper_script :: String -> String -> String -> String
1050 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1051  [
1052   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
1053   "  if $running_under_some_shell;",
1054   "# =!=!=!=!=!=!=!=!=!=!=!",
1055   "# This script is automatically generated: DO NOT EDIT!!!",
1056   "# Generated by Glasgow Haskell Compiler",
1057   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1058   "#",
1059   "$pvm_executable      = '" ++ pvm_executable ++ "';",
1060   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1061   "$SysMan = '" ++ sysMan ++ "';",
1062   "",
1063   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1064   "# first, some magical shortcuts to run "commands" on the binary",
1065   "# (which is hidden)",
1066   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1067   "    local($cmd) = $1;",
1068   "    system("$cmd $pvm_executable");",
1069   "    exit(0); # all done",
1070   "}", -}
1071   "",
1072   "# Now, run the real binary; process the args first",
1073   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
1074   "$debug = '';",
1075   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1076   "@nonPVM_args = ();",
1077   "$in_RTS_args = 0;",
1078   "",
1079   "args: while ($a = shift(@ARGV)) {",
1080   "    if ( $a eq '+RTS' ) {",
1081   "     $in_RTS_args = 1;",
1082   "    } elsif ( $a eq '-RTS' ) {",
1083   "     $in_RTS_args = 0;",
1084   "    }",
1085   "    if ( $a eq '-d' && $in_RTS_args ) {",
1086   "     $debug = '-';",
1087   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1088   "     $nprocessors = $1;",
1089   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1090   "     $nprocessors = $1;",
1091   "    } else {",
1092   "     push(@nonPVM_args, $a);",
1093   "    }",
1094   "}",
1095   "",
1096   "local($return_val) = 0;",
1097   "# Start the parallel execution by calling SysMan",
1098   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1099   "$return_val = $?;",
1100   "# ToDo: fix race condition moving files and flushing them!!",
1101   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1102   "exit($return_val);"
1103  ]
1104
1105 -----------------------------------------------------------------------------
1106 -- Complain about non-dynamic flags in OPTIONS pragmas
1107
1108 checkProcessArgsResult flags filename
1109   = do when (notNull flags) (throwDyn (ProgramError (
1110           showSDoc (hang (text filename <> char ':')
1111                       4 (text "unknown flags in  {-# OPTIONS #-} pragma:" <+>
1112                           hsep (map text flags)))
1113         )))
1114
1115 -----------------------------------------------------------------------------
1116 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1117
1118 getHCFilePackages :: FilePath -> IO [PackageId]
1119 getHCFilePackages filename =
1120   EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1121     l <- hGetLine h
1122     case l of
1123       '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1124           return (map stringToPackageId (words rest))
1125       _other ->
1126           return []
1127
1128 -----------------------------------------------------------------------------
1129 -- Static linking, of .o files
1130
1131 -- The list of packages passed to link is the list of packages on
1132 -- which this program depends, as discovered by the compilation
1133 -- manager.  It is combined with the list of packages that the user
1134 -- specifies on the command line with -package flags.  
1135 --
1136 -- In one-shot linking mode, we can't discover the package
1137 -- dependencies (because we haven't actually done any compilation or
1138 -- read any interface files), so the user must explicitly specify all
1139 -- the packages.
1140
1141 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1142 staticLink dflags o_files dep_packages = do
1143     let verb = getVerbFlag dflags
1144         output_fn = exeFileName dflags
1145
1146     -- get the full list of packages to link with, by combining the
1147     -- explicit packages with the auto packages and all of their
1148     -- dependencies, and eliminating duplicates.
1149
1150     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1151     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1152
1153     let lib_paths = libraryPaths dflags
1154     let lib_path_opts = map ("-L"++) lib_paths
1155
1156     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1157
1158 #ifdef darwin_TARGET_OS
1159     pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1160     let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1161
1162     let framework_paths = frameworkPaths dflags
1163         framework_path_opts = map ("-F"++) framework_paths
1164
1165     pkg_frameworks <- getPackageFrameworks dflags dep_packages
1166     let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1167     
1168     let frameworks = cmdlineFrameworks dflags
1169         framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1170          -- reverse because they're added in reverse order from the cmd line
1171 #endif
1172
1173         -- probably _stub.o files
1174     extra_ld_inputs <- readIORef v_Ld_inputs
1175
1176         -- opts from -optl-<blah> (including -l<blah> options)
1177     let extra_ld_opts = getOpts dflags opt_l
1178
1179     let ways = wayNames dflags
1180
1181     -- Here are some libs that need to be linked at the *end* of
1182     -- the command line, because they contain symbols that are referred to
1183     -- by the RTS.  We can't therefore use the ordinary way opts for these.
1184     let
1185         debug_opts | WayDebug `elem` ways = [ 
1186 #if defined(HAVE_LIBBFD)
1187                         "-lbfd", "-liberty"
1188 #endif
1189                          ]
1190                    | otherwise            = []
1191
1192     let
1193         thread_opts | WayThreaded `elem` ways = [ 
1194 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1195                         "-lpthread"
1196 #endif
1197 #if defined(osf3_TARGET_OS)
1198                         , "-lexc"
1199 #endif
1200                         ]
1201                     | otherwise               = []
1202
1203     let (md_c_flags, _) = machdepCCOpts dflags
1204     SysTools.runLink dflags ( 
1205                        [ SysTools.Option verb
1206                        , SysTools.Option "-o"
1207                        , SysTools.FileOption "" output_fn
1208                        ]
1209                       ++ map SysTools.Option (
1210                          md_c_flags
1211                       ++ o_files
1212                       ++ extra_ld_inputs
1213                       ++ lib_path_opts
1214                       ++ extra_ld_opts
1215 #ifdef darwin_TARGET_OS
1216                       ++ framework_path_opts
1217                       ++ framework_opts
1218 #endif
1219                       ++ pkg_lib_path_opts
1220                       ++ pkg_link_opts
1221 #ifdef darwin_TARGET_OS
1222                       ++ pkg_framework_path_opts
1223                       ++ pkg_framework_opts
1224 #endif
1225                       ++ debug_opts
1226                       ++ thread_opts
1227                     ))
1228
1229     -- parallel only: move binary to another dir -- HWL
1230     when (WayPar `elem` ways)
1231          (do success <- runPhase_MoveBinary output_fn
1232              if success then return ()
1233                         else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1234
1235
1236 exeFileName :: DynFlags -> FilePath
1237 exeFileName dflags
1238   | Just s <- outputFile dflags = 
1239 #if defined(mingw32_HOST_OS)
1240       if null (suffixOf s)
1241         then s `joinFileExt` "exe"
1242         else s
1243 #else
1244       s
1245 #endif
1246   | otherwise = 
1247 #if defined(mingw32_HOST_OS)
1248         "main.exe"
1249 #else
1250         "a.out"
1251 #endif
1252
1253 -----------------------------------------------------------------------------
1254 -- Making a DLL (only for Win32)
1255
1256 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1257 doMkDLL dflags o_files dep_packages = do
1258     let verb = getVerbFlag dflags
1259     let static = opt_Static
1260     let no_hs_main = dopt Opt_NoHsMain dflags
1261     let o_file = outputFile dflags
1262     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1263
1264     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1265     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1266
1267     let lib_paths = libraryPaths dflags
1268     let lib_path_opts = map ("-L"++) lib_paths
1269
1270     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1271
1272         -- probably _stub.o files
1273     extra_ld_inputs <- readIORef v_Ld_inputs
1274
1275         -- opts from -optdll-<blah>
1276     let extra_ld_opts = getOpts dflags opt_dll 
1277
1278     let pstate = pkgState dflags
1279         rts_id | ExtPackage id <- rtsPackageId pstate = id
1280                | otherwise = panic "staticLink: rts package missing"
1281         base_id | ExtPackage id <- basePackageId pstate = id
1282                 | otherwise = panic "staticLink: base package missing"
1283         rts_pkg  = getPackageDetails pstate rts_id
1284         base_pkg = getPackageDetails pstate base_id
1285
1286     let extra_os = if static || no_hs_main
1287                    then []
1288                    else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1289                           head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1290
1291     let (md_c_flags, _) = machdepCCOpts dflags
1292     SysTools.runMkDLL dflags
1293          ([ SysTools.Option verb
1294           , SysTools.Option "-o"
1295           , SysTools.FileOption "" output_fn
1296           ]
1297          ++ map SysTools.Option (
1298             md_c_flags
1299          ++ o_files
1300          ++ extra_os
1301          ++ [ "--target=i386-mingw32" ]
1302          ++ extra_ld_inputs
1303          ++ lib_path_opts
1304          ++ extra_ld_opts
1305          ++ pkg_lib_path_opts
1306          ++ pkg_link_opts
1307          ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1308                then [ "" ]
1309                else [ "--export-all" ])
1310         ))
1311
1312 -- -----------------------------------------------------------------------------
1313 -- Running CPP
1314
1315 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1316 doCpp dflags raw include_cc_opts input_fn output_fn = do
1317     let hscpp_opts = getOpts dflags opt_P
1318     let cmdline_include_paths = includePaths dflags
1319
1320     pkg_include_dirs <- getPackageIncludePath dflags []
1321     let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1322                           (cmdline_include_paths ++ pkg_include_dirs)
1323
1324     let verb = getVerbFlag dflags
1325
1326     let cc_opts
1327           | not include_cc_opts = []
1328           | otherwise           = (optc ++ md_c_flags)
1329                 where 
1330                       optc = getOpts dflags opt_c
1331                       (md_c_flags, _) = machdepCCOpts dflags
1332
1333     let cpp_prog args | raw       = SysTools.runCpp dflags args
1334                       | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1335
1336     let target_defs = 
1337           [ "-D" ++ HOST_OS     ++ "_BUILD_OS=1",
1338             "-D" ++ HOST_ARCH   ++ "_BUILD_ARCH=1",
1339             "-D" ++ TARGET_OS   ++ "_HOST_OS=1",
1340             "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1341         -- remember, in code we *compile*, the HOST is the same our TARGET,
1342         -- and BUILD is the same as our HOST.
1343
1344     cpp_prog       ([SysTools.Option verb]
1345                     ++ map SysTools.Option include_paths
1346                     ++ map SysTools.Option hsSourceCppOpts
1347                     ++ map SysTools.Option hscpp_opts
1348                     ++ map SysTools.Option cc_opts
1349                     ++ map SysTools.Option target_defs
1350                     ++ [ SysTools.Option     "-x"
1351                        , SysTools.Option     "c"
1352                        , SysTools.Option     input_fn
1353         -- We hackily use Option instead of FileOption here, so that the file
1354         -- name is not back-slashed on Windows.  cpp is capable of
1355         -- dealing with / in filenames, so it works fine.  Furthermore
1356         -- if we put in backslashes, cpp outputs #line directives
1357         -- with *double* backslashes.   And that in turn means that
1358         -- our error messages get double backslashes in them.
1359         -- In due course we should arrange that the lexer deals
1360         -- with these \\ escapes properly.
1361                        , SysTools.Option     "-o"
1362                        , SysTools.FileOption "" output_fn
1363                        ])
1364
1365 cHaskell1Version = "5" -- i.e., Haskell 98
1366
1367 -- Default CPP defines in Haskell source
1368 hsSourceCppOpts =
1369         [ "-D__HASKELL1__="++cHaskell1Version
1370         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
1371         , "-D__HASKELL98__"
1372         , "-D__CONCURRENT_HASKELL__"
1373         ]
1374
1375
1376 -- -----------------------------------------------------------------------------
1377 -- Misc.
1378
1379 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1380 hscNextPhase dflags HsBootFile hsc_lang  =  StopLn
1381 hscNextPhase dflags other hsc_lang = 
1382   case hsc_lang of
1383         HscC -> HCc
1384         HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1385                | otherwise -> As
1386         HscNothing     -> StopLn
1387         HscInterpreted -> StopLn
1388         _other         -> StopLn
1389
1390
1391 hscMaybeAdjustTarget :: DynFlags -> Phase -> HscSource -> HscTarget -> HscTarget
1392 hscMaybeAdjustTarget dflags stop HsBootFile current_hsc_lang 
1393   = HscNothing          -- No output (other than Foo.hi-boot) for hs-boot files
1394 hscMaybeAdjustTarget dflags stop other current_hsc_lang 
1395   = hsc_lang 
1396   where
1397         keep_hc = dopt Opt_KeepHcFiles dflags
1398         hsc_lang
1399                 -- don't change the lang if we're interpreting
1400                  | current_hsc_lang == HscInterpreted = current_hsc_lang
1401
1402                 -- force -fvia-C if we are being asked for a .hc file
1403                  | HCc <- stop = HscC
1404                  | keep_hc     = HscC
1405                 -- otherwise, stick to the plan
1406                  | otherwise = current_hsc_lang
1407
1408 GLOBAL_VAR(v_Split_info, ("",0), (String,Int))
1409         -- The split prefix and number of files