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