[project @ 2005-01-14 08:01:26 by wolfgang]
[ghc-hetmet.git] / ghc / compiler / main / DriverPipeline.hs
1 -----------------------------------------------------------------------------
2 --
3 -- GHC Driver
4 --
5 -- (c) The University of Glasgow 2002
6 --
7 -----------------------------------------------------------------------------
8
9 #include "../includes/ghcconfig.h"
10
11 module DriverPipeline (
12
13         -- Interfaces for the batch-mode driver
14    runPipeline, staticLink,
15
16         -- Interfaces for the compilation manager (interpreted/batch-mode)
17    preprocess, 
18    compile, CompResult(..), 
19    link, 
20
21         -- DLL building
22    doMkDLL
23   ) where
24
25 #include "HsVersions.h"
26
27 import Packages
28 import GetImports
29 import DriverState
30 import DriverUtil
31 import DriverMkDepend
32 import DriverPhases
33 import DriverFlags
34 import SysTools         ( newTempName, addFilesToClean, getSysMan, copy )
35 import qualified SysTools       
36 import HscMain
37 import Finder
38 import HscTypes
39 import Outputable
40 import Module
41 import ErrUtils
42 import CmdLineOpts
43 import Config
44 import RdrName          ( GlobalRdrEnv )
45 import Panic
46 import Util
47 import BasicTypes       ( SuccessFlag(..) )
48 import Maybes           ( expectJust )
49
50 import ParserCoreUtils ( getCoreModuleName )
51
52 import EXCEPTION
53 import DATA_IOREF       ( readIORef, writeIORef )
54
55 import Time             ( ClockTime )
56 import Directory
57 import System
58 import IO
59 import Monad
60 import Maybe
61
62
63 -- ---------------------------------------------------------------------------
64 -- Pre-process
65
66 -- Just preprocess a file, put the result in a temp. file (used by the
67 -- compilation manager during the summary phase).
68
69 preprocess :: DynFlags -> FilePath -> IO FilePath
70 preprocess dflags filename =
71   ASSERT(isHaskellSrcFilename filename) 
72   do runPipeline (StopBefore Hsc) dflags ("preprocess") 
73         False{-temporary output file-}
74         Nothing{-no specific output file-}
75         filename
76         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 -- The driver sits between 'compile' and 'hscMain', translating calls
89 -- to the former into calls to the latter, and results from the latter
90 -- into results from the former.  It does things like preprocessing
91 -- the .hs file if necessary, and compiling up the .stub_c files to
92 -- generate Linkables.
93
94 -- NB.  No old interface can also mean that the source has changed.
95
96 compile :: HscEnv
97         -> Module
98         -> ModLocation
99         -> ClockTime               -- timestamp of original source file
100         -> Bool                    -- True <=> source unchanged
101         -> Bool                    -- True <=> have object
102         -> Maybe ModIface          -- old interface, if available
103         -> IO CompResult
104
105 data CompResult
106    = CompOK   ModDetails                -- New details
107               (Maybe GlobalRdrEnv)      -- Lexical environment for the module
108                                         -- (Maybe because we may have loaded it from
109                                         --  its precompiled interface)
110               ModIface                  -- New iface
111               (Maybe Linkable)  -- New code; Nothing => compilation was not reqd
112                                 --                      (old code is still valid)
113
114    | CompErrs 
115
116
117 compile hsc_env this_mod location src_timestamp
118         source_unchanged have_object 
119         old_iface = do 
120
121    let dyn_flags = hsc_dflags hsc_env
122
123    showPass dyn_flags
124         (showSDoc (text "Compiling" <+> ppr this_mod))
125
126    let verb       = verbosity dyn_flags
127    let input_fn   = expectJust "compile:hs" (ml_hs_file location) 
128    let input_fnpp = expectJust "compile:hspp" (ml_hspp_file location)
129
130    when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
131
132    -- add in the OPTIONS from the source file
133    opts <- getOptionsFromSource input_fnpp
134    (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
135    checkProcessArgsResult unhandled_flags input_fn
136
137    let (basename, _) = splitFilename input_fn
138
139   -- We add the directory in which the .hs files resides) to the import path.
140   -- This is needed when we try to compile the .hc file later, if it
141   -- imports a _stub.h file that we created here.
142    let current_dir = directoryOf basename
143    old_paths <- readIORef v_Include_paths
144    writeIORef v_Include_paths (current_dir : old_paths)
145    -- put back the old include paths afterward.
146    later (writeIORef v_Include_paths old_paths) $ do
147
148    -- figure out what lang we're generating
149    hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
150    -- figure out what the next phase should be
151    next_phase <- hscNextPhase hsc_lang
152    -- figure out what file to generate the output into
153    get_output_fn <- genOutputFilenameFunc False Nothing next_phase basename
154    output_fn <- get_output_fn next_phase (Just location)
155
156    let dyn_flags' = dyn_flags { hscLang = hsc_lang,
157                                 hscOutName = output_fn,
158                                 hscStubCOutName = basename ++ "_stub.c",
159                                 hscStubHOutName = basename ++ "_stub.h",
160                                 extCoreName = basename ++ ".hcr" }
161
162    -- -no-recomp should also work with --make
163    do_recomp <- readIORef v_Recomp
164    let source_unchanged' = source_unchanged && do_recomp
165        hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
166
167    -- run the compiler
168    hsc_result <- hscMain hsc_env' printErrorsAndWarnings this_mod location
169                          source_unchanged' have_object old_iface
170
171    case hsc_result of
172       HscFail -> return CompErrs
173
174       HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
175
176       HscRecomp details rdr_env iface
177         stub_h_exists stub_c_exists maybe_interpreted_code -> do
178            let 
179            maybe_stub_o <- compileStub dyn_flags' stub_c_exists
180            let stub_unlinked = case maybe_stub_o of
181                                   Nothing -> []
182                                   Just stub_o -> [ DotO stub_o ]
183
184            (hs_unlinked, unlinked_time) <-
185              case hsc_lang of
186
187                 -- in interpreted mode, just return the compiled code
188                 -- as our "unlinked" object.
189                 HscInterpreted -> 
190                     case maybe_interpreted_code of
191 #ifdef GHCI
192                        Just comp_bc -> return ([BCOs comp_bc], src_timestamp)
193                         -- Why do we use the timestamp of the source file here,
194                         -- rather than the current time?  This works better in
195                         -- the case where the local clock is out of sync
196                         -- with the filesystem's clock.  It's just as accurate:
197                         -- if the source is modified, then the linkable will
198                         -- be out of date.
199 #endif
200                        Nothing -> panic "compile: no interpreted code"
201
202                 -- we're in batch mode: finish the compilation pipeline.
203                 _other -> do
204                    let object_filename = ml_obj_file location
205
206                    runPipeline (StopBefore Ln) dyn_flags ""
207                         True Nothing output_fn (Just location)
208                         -- the object filename comes from the ModLocation
209
210                    o_time <- getModificationTime object_filename
211                    return ([DotO object_filename], o_time)
212
213            let linkable = LM unlinked_time this_mod
214                              (hs_unlinked ++ stub_unlinked)
215
216            return (CompOK details rdr_env iface (Just linkable))
217
218 -----------------------------------------------------------------------------
219 -- stub .h and .c files (for foreign export support)
220
221 compileStub dflags stub_c_exists
222   | not stub_c_exists = return Nothing
223   | stub_c_exists = do
224         -- compile the _stub.c file w/ gcc
225         let stub_c = hscStubCOutName dflags
226         stub_o <- runPipeline (StopBefore Ln) dflags "stub-compile"
227                         True{-persistent output-} 
228                         Nothing{-no specific output file-}
229                         stub_c
230                         Nothing{-no ModLocation-}
231         return (Just stub_o)
232
233
234 -- ---------------------------------------------------------------------------
235 -- Link
236
237 link :: GhciMode                -- interactive or batch
238      -> DynFlags                -- dynamic flags
239      -> Bool                    -- attempt linking in batch mode?
240      -> HomePackageTable        -- what to link
241      -> IO SuccessFlag
242
243 -- For the moment, in the batch linker, we don't bother to tell doLink
244 -- which packages to link -- it just tries all that are available.
245 -- batch_attempt_linking should only be *looked at* in batch mode.  It
246 -- should only be True if the upsweep was successful and someone
247 -- exports main, i.e., we have good reason to believe that linking
248 -- will succeed.
249
250 #ifdef GHCI
251 link Interactive dflags batch_attempt_linking hpt
252     = do -- Not Linking...(demand linker will do the job)
253          return Succeeded
254 #endif
255
256 link Batch dflags batch_attempt_linking hpt
257    | batch_attempt_linking
258    = do 
259         let 
260             home_mod_infos = moduleEnvElts hpt
261
262             -- the packages we depend on
263             pkg_deps  = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
264
265             -- the linkables to link
266             linkables = map hm_linkable home_mod_infos
267
268         when (verb >= 3) $ do
269              hPutStrLn stderr "link: linkables are ..."
270              hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
271
272         -- check for the -no-link flag
273         omit_linking <- readIORef v_NoLink
274         if omit_linking 
275           then do when (verb >= 3) $
276                     hPutStrLn stderr "link(batch): linking omitted (-no-link flag given)."
277                   return Succeeded
278           else do
279
280         when (verb >= 1) $
281              hPutStrLn stderr "Linking ..."
282
283         let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
284             obj_files = concatMap getOfiles linkables
285
286         -- Don't showPass in Batch mode; doLink will do that for us.
287         staticLink dflags obj_files pkg_deps
288
289         when (verb >= 3) (hPutStrLn stderr "link: done")
290
291         -- staticLink only returns if it succeeds
292         return Succeeded
293
294    | otherwise
295    = do when (verb >= 3) $ do
296             hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
297             hPutStrLn stderr "   Main.main not exported; not linking."
298         return Succeeded
299    where
300       verb = verbosity dflags
301       
302 -- ---------------------------------------------------------------------------
303 -- Run a compilation pipeline, consisting of multiple phases.
304
305 -- The DynFlags can be modified by phases in the pipeline (eg. by
306 -- OPTIONS pragmas), and the changes affect later phases in the
307 -- pipeline, but we throw away the resulting DynFlags at the end.
308
309 runPipeline
310   :: GhcMode            -- when to stop
311   -> DynFlags           -- dynamic flags
312   -> String             -- "stop after" flag
313   -> Bool               -- final output is persistent?
314   -> Maybe FilePath     -- where to put the output, optionally
315   -> FilePath           -- input filename
316   -> Maybe ModLocation  -- a ModLocation for this module, if we have one
317   -> IO FilePath        -- output filename
318
319 runPipeline todo dflags stop_flag keep_output 
320   maybe_output_filename input_fn maybe_loc
321   = do
322   split <- readIORef v_Split_object_files
323   let (basename, suffix) = splitFilename input_fn
324       start_phase = startPhase suffix
325
326       stop_phase = case todo of 
327                         StopBefore As | split -> SplitAs
328                         StopBefore phase      -> phase
329                         DoMkDependHS          -> Ln
330                         DoLink                -> Ln
331                         DoMkDLL               -> Ln
332
333   -- We want to catch cases of "you can't get there from here" before
334   -- we start the pipeline, because otherwise it will just run off the
335   -- end.
336   --
337   -- There is a partial ordering on phases, where A < B iff A occurs
338   -- before B in a normal compilation pipeline.
339   --
340   when (not (start_phase `happensBefore` stop_phase)) $
341         throwDyn (UsageError 
342                     ("flag `" ++ stop_flag
343                      ++ "' is incompatible with source file `"
344                      ++ input_fn ++ "'"))
345
346   -- generate a function which will be used to calculate output file names
347   -- as we go along.
348   get_output_fn <- genOutputFilenameFunc keep_output maybe_output_filename
349                         stop_phase basename
350
351   -- and execute the pipeline...
352   (output_fn, maybe_loc) <- 
353         pipeLoop dflags start_phase stop_phase input_fn basename suffix 
354                  get_output_fn maybe_loc
355
356   -- sometimes, a compilation phase doesn't actually generate any output
357   -- (eg. the CPP phase when -fcpp is not turned on).  If we end on this
358   -- stage, but we wanted to keep the output, then we have to explicitly
359   -- copy the file.
360   if keep_output
361         then do final_fn <- get_output_fn stop_phase maybe_loc
362                 when (final_fn /= output_fn) $
363                   copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
364                         ++ "'") output_fn final_fn
365                 return final_fn
366         else
367              return output_fn
368
369
370 pipeLoop :: DynFlags -> Phase -> Phase -> FilePath -> String -> Suffix
371   -> (Phase -> Maybe ModLocation -> IO FilePath)
372   -> Maybe ModLocation -> IO (FilePath, Maybe ModLocation)
373
374 pipeLoop dflags phase stop_phase input_fn orig_basename orig_suff 
375         get_output_fn maybe_loc
376
377   | phase == stop_phase  =  return (input_fn, maybe_loc)  -- all done
378
379   | not (phase `happensBefore` stop_phase)  = 
380         -- Something has gone wrong.  We'll try to cover all the cases when
381         -- this could happen, so if we reach here it is a panic.
382         -- eg. it might happen if the -C flag is used on a source file that
383         -- has {-# OPTIONS -fasm #-}.
384         panic ("pipeLoop: at phase " ++ show phase ++ 
385                 " but I wanted to stop at phase " ++ show stop_phase)
386
387   | otherwise = do
388         maybe_next_phase <- runPhase phase dflags orig_basename 
389                                 orig_suff input_fn get_output_fn maybe_loc
390         case maybe_next_phase of
391           (Nothing, dflags, maybe_loc, output_fn) -> do
392                 -- we stopped early, but return the *final* filename
393                 -- (it presumably already exists)
394                 final_fn <- get_output_fn stop_phase maybe_loc
395                 return (final_fn, maybe_loc)
396           (Just next_phase, dflags', maybe_loc, output_fn) ->
397                 pipeLoop dflags' next_phase stop_phase output_fn
398                         orig_basename orig_suff get_output_fn maybe_loc
399
400   
401 genOutputFilenameFunc :: Bool -> Maybe FilePath -> Phase -> String
402   -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
403 genOutputFilenameFunc keep_final_output maybe_output_filename 
404                 stop_phase basename
405  = do
406    hcsuf      <- readIORef v_HC_suf
407    odir       <- readIORef v_Output_dir
408    osuf       <- readIORef v_Object_suf
409    keep_hc    <- readIORef v_Keep_hc_files
410 #ifdef ILX
411    keep_il    <- readIORef v_Keep_il_files
412    keep_ilx   <- readIORef v_Keep_ilx_files
413 #endif
414    keep_raw_s <- readIORef v_Keep_raw_s_files
415    keep_s     <- readIORef v_Keep_s_files
416    let
417         myPhaseInputExt HCc | Just s <- hcsuf = s
418         myPhaseInputExt Ln    = osuf
419         myPhaseInputExt other = phaseInputExt other
420
421         func next_phase maybe_location
422                 | is_last_phase, Just f <- maybe_output_filename = return f
423                 | is_last_phase && keep_final_output = persistent_fn
424                 | keep_this_output                   = persistent_fn
425                 | otherwise                          = newTempName suffix
426
427            where
428                 is_last_phase = next_phase == stop_phase
429
430                 -- sometimes, we keep output from intermediate stages
431                 keep_this_output = 
432                      case next_phase of
433                              Ln                  -> True
434                              Mangle | keep_raw_s -> True
435                              As     | keep_s     -> True
436                              HCc    | keep_hc    -> True
437                              _other              -> False
438
439                 suffix = myPhaseInputExt next_phase
440
441                 -- persistent object files get put in odir
442                 persistent_fn 
443                    | Ln <- next_phase  = return odir_persistent
444                    | otherwise         = return persistent
445
446                 persistent = basename ++ '.':suffix
447
448                 odir_persistent
449                    | Just loc <- maybe_location = ml_obj_file loc
450                    | Just d <- odir = replaceFilenameDirectory persistent d
451                    | otherwise      = persistent
452
453    return func
454
455
456 -- -----------------------------------------------------------------------------
457 -- Each phase in the pipeline returns the next phase to execute, and the
458 -- name of the file in which the output was placed.
459 --
460 -- We must do things dynamically this way, because we often don't know
461 -- what the rest of the phases will be until part-way through the
462 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
463 -- of a source file can change the latter stages of the pipeline from
464 -- taking the via-C route to using the native code generator.
465
466 runPhase :: Phase
467          -> DynFlags
468          -> String      -- basename of original input source
469          -> String      -- its extension
470          -> FilePath    -- name of file which contains the input to this phase.
471          -> (Phase -> Maybe ModLocation -> IO FilePath)
472                         -- how to calculate the output filename
473          -> Maybe ModLocation           -- the ModLocation, if we have one
474          -> IO (Maybe Phase,            -- next phase
475                 DynFlags,               -- new dynamic flags
476                 Maybe ModLocation,      -- the ModLocation, if we have one
477                 FilePath)               -- output filename
478
479 -------------------------------------------------------------------------------
480 -- Unlit phase 
481
482 runPhase Unlit dflags _basename _suff input_fn get_output_fn maybe_loc
483   = do let unlit_flags = getOpts dflags opt_L
484        -- The -h option passes the file name for unlit to put in a #line directive
485        output_fn <- get_output_fn Cpp maybe_loc
486
487        SysTools.runUnlit dflags 
488                 (map SysTools.Option unlit_flags ++
489                           [ SysTools.Option     "-h"
490                           , SysTools.Option     input_fn
491                           , SysTools.FileOption "" input_fn
492                           , SysTools.FileOption "" output_fn
493                           ])
494
495        return (Just Cpp, dflags, maybe_loc, output_fn)
496
497 -------------------------------------------------------------------------------
498 -- Cpp phase 
499
500 runPhase Cpp dflags basename suff input_fn get_output_fn maybe_loc
501   = do src_opts <- getOptionsFromSource input_fn
502        (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
503        checkProcessArgsResult unhandled_flags (basename++'.':suff)
504
505        if not (cppFlag dflags) then
506            -- no need to preprocess CPP, just pass input file along
507            -- to the next phase of the pipeline.
508           return (Just HsPp, dflags, maybe_loc, input_fn)
509         else do
510             output_fn <- get_output_fn HsPp maybe_loc
511             doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
512             return (Just HsPp, dflags, maybe_loc, output_fn)
513
514 -------------------------------------------------------------------------------
515 -- HsPp phase 
516
517 runPhase HsPp dflags basename suff input_fn get_output_fn maybe_loc
518   = do if not (ppFlag dflags) then
519            -- no need to preprocess, just pass input file along
520            -- to the next phase of the pipeline.
521           return (Just Hsc, dflags, maybe_loc, input_fn)
522         else do
523             let hspp_opts = getOpts dflags opt_F
524             hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
525             let orig_fn = basename ++ '.':suff
526             output_fn <- get_output_fn Hsc maybe_loc
527             SysTools.runPp dflags
528                            ( [ SysTools.Option     orig_fn
529                              , SysTools.Option     input_fn
530                              , SysTools.FileOption "" output_fn
531                              ] ++
532                              map SysTools.Option hs_src_pp_opts ++
533                              map SysTools.Option hspp_opts
534                            )
535             return (Just Hsc, dflags, maybe_loc, output_fn)
536
537 -----------------------------------------------------------------------------
538 -- Hsc phase
539
540 -- Compilation of a single module, in "legacy" mode (_not_ under
541 -- the direction of the compilation manager).
542 runPhase Hsc dflags basename suff input_fn get_output_fn _maybe_loc = do
543   todo <- readIORef v_GhcMode
544   if todo == DoMkDependHS then do
545        locn <- doMkDependHSPhase dflags basename suff input_fn
546        return (Nothing, dflags, Just locn, input_fn)  -- Ln is a dummy stop phase 
547
548    else do
549       -- normal Hsc mode, not mkdependHS
550
551   -- we add the current directory (i.e. the directory in which
552   -- the .hs files resides) to the import path, since this is
553   -- what gcc does, and it's probably what you want.
554         let current_dir = directoryOf basename
555         
556         paths <- readIORef v_Include_paths
557         writeIORef v_Include_paths (current_dir : paths)
558         
559   -- gather the imports and module name
560         (_,_,mod_name) <- 
561             if isExtCoreFilename ('.':suff)
562              then do
563                -- no explicit imports in ExtCore input.
564                m <- getCoreModuleName input_fn
565                return ([], [], mkModule m)
566              else 
567                getImportsFromFile input_fn
568
569   -- build a ModLocation to pass to hscMain.
570         location' <- mkHomeModLocation mod_name (basename ++ '.':suff)
571
572   -- take -ohi into account if present
573         ohi <- readIORef v_Output_hi
574         let location | Just fn <- ohi = location'{ ml_hi_file = fn }
575                      | otherwise      = location'
576
577   -- figure out if the source has changed, for recompilation avoidance.
578   -- only do this if we're eventually going to generate a .o file.
579   -- (ToDo: do when generating .hc files too?)
580   --
581   -- Setting source_unchanged to True means that M.o seems
582   -- to be up to date wrt M.hs; so no need to recompile unless imports have
583   -- changed (which the compiler itself figures out).
584   -- Setting source_unchanged to False tells the compiler that M.o is out of
585   -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
586         do_recomp   <- readIORef v_Recomp
587         expl_o_file <- readIORef v_Output_file
588
589         let o_file -- if the -o option is given and IT IS THE OBJECT FILE FOR
590                    -- THIS COMPILATION, then use that to determine if the 
591                    -- source is unchanged.
592                 | Just x <- expl_o_file, todo == StopBefore Ln  =  x
593                 | otherwise = ml_obj_file location
594
595         source_unchanged <- 
596           if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
597              then return False
598              else do t1 <- getModificationTime (basename ++ '.':suff)
599                      o_file_exists <- doesFileExist o_file
600                      if not o_file_exists
601                         then return False       -- Need to recompile
602                         else do t2 <- getModificationTime o_file
603                                 if t2 > t1
604                                   then return True
605                                   else return False
606
607   -- get the DynFlags
608         hsc_lang <- hscMaybeAdjustLang (hscLang dflags)
609         next_phase <- hscNextPhase hsc_lang
610         output_fn <- get_output_fn next_phase (Just location)
611
612         let dflags' = dflags { hscLang = hsc_lang,
613                                hscOutName = output_fn,
614                                hscStubCOutName = basename ++ "_stub.c",
615                                hscStubHOutName = basename ++ "_stub.h",
616                                extCoreName = basename ++ ".hcr" }
617         hsc_env <- newHscEnv OneShot dflags'
618
619   -- run the compiler!
620         result <- hscMain hsc_env printErrorsAndWarnings mod_name
621                           location{ ml_hspp_file=Just input_fn }
622                           source_unchanged
623                           False
624                           Nothing        -- no iface
625
626         case result of
627
628             HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
629
630             HscNoRecomp details iface -> do
631                 SysTools.touch dflags' "Touching object file" o_file
632                 return (Nothing, dflags', Just location, output_fn)
633
634             HscRecomp _details _rdr_env _iface 
635                       stub_h_exists stub_c_exists
636                       _maybe_interpreted_code -> do
637
638                 -- deal with stubs
639                 maybe_stub_o <- compileStub dflags' stub_c_exists
640                 case maybe_stub_o of
641                       Nothing -> return ()
642                       Just stub_o -> add v_Ld_inputs stub_o
643                 case hscLang dflags' of
644                       HscNothing -> return (Nothing, dflags', Just location, output_fn)
645                       _ -> return (Just next_phase, dflags', Just location, output_fn)
646
647 -----------------------------------------------------------------------------
648 -- Cmm phase
649
650 runPhase CmmCpp dflags basename suff input_fn get_output_fn maybe_loc
651   = do
652        output_fn <- get_output_fn Cmm maybe_loc
653        doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn 
654        return (Just Cmm, dflags, maybe_loc, output_fn)
655
656 runPhase Cmm dflags basename suff input_fn get_output_fn maybe_loc
657   = do
658         hsc_lang <- hscMaybeAdjustLang (hscLang dflags)
659         next_phase <- hscNextPhase hsc_lang
660         output_fn <- get_output_fn next_phase maybe_loc
661
662         let dflags' = dflags { hscLang = hsc_lang,
663                                hscOutName = output_fn,
664                                hscStubCOutName = basename ++ "_stub.c",
665                                hscStubHOutName = basename ++ "_stub.h",
666                                extCoreName = basename ++ ".hcr" }
667
668         ok <- hscCmmFile dflags' input_fn
669
670         when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
671
672         return (Just next_phase, dflags, maybe_loc, output_fn)
673
674 -----------------------------------------------------------------------------
675 -- Cc phase
676
677 -- we don't support preprocessing .c files (with -E) now.  Doing so introduces
678 -- way too many hacks, and I can't say I've ever used it anyway.
679
680 runPhase cc_phase dflags basename suff input_fn get_output_fn maybe_loc
681    | cc_phase == Cc || cc_phase == HCc
682    = do let cc_opts = getOpts dflags opt_c
683         cmdline_include_paths <- readIORef v_Include_paths
684
685         split  <- readIORef v_Split_object_files
686         mangle <- readIORef v_Do_asm_mangling
687
688         let hcc = cc_phase == HCc
689
690             next_phase
691                 | hcc && mangle     = Mangle
692                 | otherwise         = As
693
694         output_fn <- get_output_fn next_phase maybe_loc
695
696         -- HC files have the dependent packages stamped into them
697         pkgs <- if hcc then getHCFilePackages input_fn else return []
698
699         -- add package include paths even if we're just compiling .c
700         -- files; this is the Value Add(TM) that using ghc instead of
701         -- gcc gives you :)
702         pkg_include_dirs <- getPackageIncludePath dflags pkgs
703         let include_paths = foldr (\ x xs -> "-I" : x : xs) []
704                               (cmdline_include_paths ++ pkg_include_dirs)
705
706         mangle <- readIORef v_Do_asm_mangling
707         (md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
708
709         let verb = getVerbFlag dflags
710
711         pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
712
713         split_objs <- readIORef v_Split_object_files
714         let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
715                       | otherwise         = [ ]
716
717         excessPrecision <- readIORef v_Excess_precision
718
719         -- force the C compiler to interpret this file as C when
720         -- compiling .hc files, by adding the -x c option.
721         let langopt
722                 | cc_phase == HCc = [ SysTools.Option "-x", SysTools.Option "c"]
723                 | otherwise       = [ ]
724
725         SysTools.runCc dflags (langopt ++
726                         [ SysTools.FileOption "" input_fn
727                         , SysTools.Option "-o"
728                         , SysTools.FileOption "" output_fn
729                         ]
730                        ++ map SysTools.Option (
731                           md_c_flags
732                        ++ (if cc_phase == HCc && mangle
733                              then md_regd_c_flags
734                              else [])
735                        ++ [ verb, "-S", "-Wimplicit", "-O" ]
736                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
737                        ++ cc_opts
738                        ++ split_opt
739                        ++ (if excessPrecision then [] else [ "-ffloat-store" ])
740                        ++ include_paths
741                        ++ pkg_extra_cc_opts
742                        ))
743
744         return (Just next_phase, dflags, maybe_loc, output_fn)
745
746         -- ToDo: postprocess the output from gcc
747
748 -----------------------------------------------------------------------------
749 -- Mangle phase
750
751 runPhase Mangle dflags _basename _suff input_fn get_output_fn maybe_loc
752    = do let mangler_opts = getOpts dflags opt_m
753         machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
754                           then do let n_regs = stolen_x86_regs dflags
755                                   return [ show n_regs ]
756                           else return []
757
758         split <- readIORef v_Split_object_files
759         let next_phase
760                 | split = SplitMangle
761                 | otherwise = As
762         output_fn <- get_output_fn next_phase maybe_loc
763
764         SysTools.runMangle dflags (map SysTools.Option mangler_opts
765                           ++ [ SysTools.FileOption "" input_fn
766                              , SysTools.FileOption "" output_fn
767                              ]
768                           ++ map SysTools.Option machdep_opts)
769
770         return (Just next_phase, dflags, maybe_loc, output_fn)
771
772 -----------------------------------------------------------------------------
773 -- Splitting phase
774
775 runPhase SplitMangle dflags _basename _suff input_fn get_output_fn maybe_loc
776   = do  -- tmp_pfx is the prefix used for the split .s files
777         -- We also use it as the file to contain the no. of split .s files (sigh)
778         split_s_prefix <- SysTools.newTempName "split"
779         let n_files_fn = split_s_prefix
780
781         SysTools.runSplit dflags
782                           [ SysTools.FileOption "" input_fn
783                           , SysTools.FileOption "" split_s_prefix
784                           , SysTools.FileOption "" n_files_fn
785                           ]
786
787         -- Save the number of split files for future references
788         s <- readFile n_files_fn
789         let n_files = read s :: Int
790         writeIORef v_Split_info (split_s_prefix, n_files)
791
792         -- Remember to delete all these files
793         addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
794                         | n <- [1..n_files]]
795
796         return (Just SplitAs, dflags, maybe_loc, "**splitmangle**")
797           -- we don't use the filename
798
799 -----------------------------------------------------------------------------
800 -- As phase
801
802 runPhase As dflags _basename _suff input_fn get_output_fn maybe_loc
803   = do  let as_opts =  getOpts dflags opt_a
804         cmdline_include_paths <- readIORef v_Include_paths
805
806         output_fn <- get_output_fn Ln maybe_loc
807
808         -- we create directories for the object file, because it
809         -- might be a hierarchical module.
810         createDirectoryHierarchy (directoryOf output_fn)
811
812         SysTools.runAs dflags   
813                        (map SysTools.Option as_opts
814                        ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
815                        ++ [ SysTools.Option "-c"
816                           , SysTools.FileOption "" input_fn
817                           , SysTools.Option "-o"
818                           , SysTools.FileOption "" output_fn
819                           ])
820
821         return (Just Ln, dflags, maybe_loc, output_fn)
822
823
824 runPhase SplitAs dflags basename _suff _input_fn get_output_fn maybe_loc
825   = do  let as_opts = getOpts dflags opt_a
826
827         (split_s_prefix, n) <- readIORef v_Split_info
828
829         odir <- readIORef v_Output_dir
830         let real_odir = case odir of
831                                 Nothing -> basename ++ "_split"
832                                 Just d  -> d
833
834         let assemble_file n
835               = do  let input_s  = split_s_prefix ++ "__" ++ show n ++ ".s"
836                     let output_o = replaceFilenameDirectory
837                                         (basename ++ "__" ++ show n ++ ".o")
838                                          real_odir
839                     real_o <- osuf_ify output_o
840                     SysTools.runAs dflags
841                                  (map SysTools.Option as_opts ++
842                                     [ SysTools.Option "-c"
843                                     , SysTools.Option "-o"
844                                     , SysTools.FileOption "" real_o
845                                     , SysTools.FileOption "" input_s
846                                     ])
847         
848         mapM_ assemble_file [1..n]
849
850         output_fn <- get_output_fn Ln maybe_loc
851         return (Just Ln, dflags, maybe_loc, output_fn)
852
853 #ifdef ILX
854 -----------------------------------------------------------------------------
855 -- Ilx2Il phase
856 -- Run ilx2il over the ILX output, getting an IL file
857
858 runPhase Ilx2Il dflags _basename _suff input_fn get_output_fn maybe_loc
859   = do  let ilx2il_opts = getOpts dflags opt_I
860         SysTools.runIlx2il (map SysTools.Option ilx2il_opts
861                            ++ [ SysTools.Option "--no-add-suffix-to-assembly",
862                                 SysTools.Option "mscorlib",
863                                 SysTools.Option "-o",
864                                 SysTools.FileOption "" output_fn,
865                                 SysTools.FileOption "" input_fn ])
866         return True
867
868 -----------------------------------------------------------------------------
869 -- Ilasm phase
870 -- Run ilasm over the IL, getting a DLL
871
872 runPhase Ilasm dflags _basename _suff input_fn get_output_fn maybe_loc
873   = do  let ilasm_opts = getOpts dflags opt_i
874         SysTools.runIlasm (map SysTools.Option ilasm_opts
875                            ++ [ SysTools.Option "/QUIET",
876                                 SysTools.Option "/DLL",
877                                 SysTools.FileOption "/OUT=" output_fn,
878                                 SysTools.FileOption "" input_fn ])
879         return True
880
881 #endif /* ILX */
882
883 -----------------------------------------------------------------------------
884 -- MoveBinary sort-of-phase
885 -- After having produced a binary, move it somewhere else and generate a
886 -- wrapper script calling the binary. Currently, we need this only in 
887 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
888 -- central directory.
889 -- This is called from staticLink below, after linking. I haven't made it
890 -- a separate phase to minimise interfering with other modules, and
891 -- we don't need the generality of a phase (MoveBinary is always
892 -- done after linking and makes only sense in a parallel setup)   -- HWL
893
894 runPhase_MoveBinary input_fn
895   = do  
896         sysMan   <- getSysMan
897         pvm_root <- getEnv "PVM_ROOT"
898         pvm_arch <- getEnv "PVM_ARCH"
899         let 
900            pvm_executable_base = "=" ++ input_fn
901            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
902         -- nuke old binary; maybe use configur'ed names for cp and rm?
903         system ("rm -f " ++ pvm_executable)
904         -- move the newly created binary into PVM land
905         system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
906         -- generate a wrapper script for running a parallel prg under PVM
907         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
908         return True
909
910 -- generates a Perl skript starting a parallel prg under PVM
911 mk_pvm_wrapper_script :: String -> String -> String -> String
912 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
913  [
914   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
915   "  if $running_under_some_shell;",
916   "# =!=!=!=!=!=!=!=!=!=!=!",
917   "# This script is automatically generated: DO NOT EDIT!!!",
918   "# Generated by Glasgow Haskell Compiler",
919   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
920   "#",
921   "$pvm_executable      = '" ++ pvm_executable ++ "';",
922   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
923   "$SysMan = '" ++ sysMan ++ "';",
924   "",
925   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
926   "# first, some magical shortcuts to run "commands" on the binary",
927   "# (which is hidden)",
928   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
929   "    local($cmd) = $1;",
930   "    system("$cmd $pvm_executable");",
931   "    exit(0); # all done",
932   "}", -}
933   "",
934   "# Now, run the real binary; process the args first",
935   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
936   "$debug = '';",
937   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
938   "@nonPVM_args = ();",
939   "$in_RTS_args = 0;",
940   "",
941   "args: while ($a = shift(@ARGV)) {",
942   "    if ( $a eq '+RTS' ) {",
943   "     $in_RTS_args = 1;",
944   "    } elsif ( $a eq '-RTS' ) {",
945   "     $in_RTS_args = 0;",
946   "    }",
947   "    if ( $a eq '-d' && $in_RTS_args ) {",
948   "     $debug = '-';",
949   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
950   "     $nprocessors = $1;",
951   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
952   "     $nprocessors = $1;",
953   "    } else {",
954   "     push(@nonPVM_args, $a);",
955   "    }",
956   "}",
957   "",
958   "local($return_val) = 0;",
959   "# Start the parallel execution by calling SysMan",
960   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
961   "$return_val = $?;",
962   "# ToDo: fix race condition moving files and flushing them!!",
963   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
964   "exit($return_val);"
965  ]
966
967 -----------------------------------------------------------------------------
968 -- Complain about non-dynamic flags in OPTIONS pragmas
969
970 checkProcessArgsResult flags filename
971   = do when (notNull flags) (throwDyn (ProgramError (
972           showSDoc (hang (text filename <> char ':')
973                       4 (text "unknown flags in  {-# OPTIONS #-} pragma:" <+>
974                           hsep (map text flags)))
975         )))
976
977 -----------------------------------------------------------------------------
978 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
979
980 getHCFilePackages :: FilePath -> IO [PackageId]
981 getHCFilePackages filename =
982   EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
983     l <- hGetLine h
984     case l of
985       '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
986           return (map stringToPackageId (words rest))
987       _other ->
988           return []
989
990 -----------------------------------------------------------------------------
991 -- Static linking, of .o files
992
993 -- The list of packages passed to link is the list of packages on
994 -- which this program depends, as discovered by the compilation
995 -- manager.  It is combined with the list of packages that the user
996 -- specifies on the command line with -package flags.  
997 --
998 -- In one-shot linking mode, we can't discover the package
999 -- dependencies (because we haven't actually done any compilation or
1000 -- read any interface files), so the user must explicitly specify all
1001 -- the packages.
1002
1003 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1004 staticLink dflags o_files dep_packages = do
1005     let verb = getVerbFlag dflags
1006     static     <- readIORef v_Static
1007     no_hs_main <- readIORef v_NoHsMain
1008
1009     -- get the full list of packages to link with, by combining the
1010     -- explicit packages with the auto packages and all of their
1011     -- dependencies, and eliminating duplicates.
1012
1013     o_file <- readIORef v_Output_file
1014 #if defined(mingw32_HOST_OS)
1015     let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1016 #else
1017     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1018 #endif
1019
1020     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1021     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1022
1023     lib_paths <- readIORef v_Library_paths
1024     let lib_path_opts = map ("-L"++) lib_paths
1025
1026     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1027
1028 #ifdef darwin_TARGET_OS
1029     pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1030     let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1031
1032     framework_paths <- readIORef v_Framework_paths
1033     let framework_path_opts = map ("-F"++) framework_paths
1034
1035     pkg_frameworks <- getPackageFrameworks dflags dep_packages
1036     let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1037
1038     frameworks <- readIORef v_Cmdline_frameworks
1039     let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1040          -- reverse because they're added in reverse order from the cmd line
1041 #endif
1042
1043         -- probably _stub.o files
1044     extra_ld_inputs <- readIORef v_Ld_inputs
1045
1046         -- opts from -optl-<blah> (including -l<blah> options)
1047     extra_ld_opts <- getStaticOpts v_Opt_l
1048
1049     let pstate = pkgState dflags
1050         rts_id | Just id <- rtsPackageId pstate = id
1051                | otherwise = panic "staticLink: rts package missing"
1052         base_id | Just id <- basePackageId pstate = id
1053                 | otherwise = panic "staticLink: base package missing"
1054         rts_pkg  = getPackageDetails pstate rts_id
1055         base_pkg = getPackageDetails pstate base_id
1056
1057     ways <- readIORef v_Ways
1058
1059     -- Here are some libs that need to be linked at the *end* of
1060     -- the command line, because they contain symbols that are referred to
1061     -- by the RTS.  We can't therefore use the ordinary way opts for these.
1062     let
1063         debug_opts | WayDebug `elem` ways = [ 
1064 #if defined(HAVE_LIBBFD)
1065                         "-lbfd", "-liberty"
1066 #endif
1067                          ]
1068                    | otherwise            = []
1069
1070     let
1071         thread_opts | WayThreaded `elem` ways = [ 
1072 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1073                         "-lpthread"
1074 #endif
1075 #if defined(osf3_TARGET_OS)
1076                         , "-lexc"
1077 #endif
1078                         ]
1079                     | otherwise               = []
1080
1081     let extra_os = if static || no_hs_main
1082                    then []
1083                    else []
1084
1085     (md_c_flags, _) <- machdepCCOpts dflags
1086     SysTools.runLink dflags ( 
1087                        [ SysTools.Option verb
1088                        , SysTools.Option "-o"
1089                        , SysTools.FileOption "" output_fn
1090                        ]
1091                       ++ map SysTools.Option (
1092                          md_c_flags
1093                       ++ o_files
1094                       ++ extra_os
1095                       ++ extra_ld_inputs
1096                       ++ lib_path_opts
1097                       ++ extra_ld_opts
1098 #ifdef darwin_TARGET_OS
1099                       ++ framework_path_opts
1100                       ++ framework_opts
1101 #endif
1102                       ++ pkg_lib_path_opts
1103                       ++ pkg_link_opts
1104 #ifdef darwin_TARGET_OS
1105                       ++ pkg_framework_path_opts
1106                       ++ pkg_framework_opts
1107 #endif
1108                       ++ debug_opts
1109                       ++ thread_opts
1110                     ))
1111
1112     -- parallel only: move binary to another dir -- HWL
1113     ways_ <- readIORef v_Ways
1114     when (WayPar `elem` ways_)
1115          (do success <- runPhase_MoveBinary output_fn
1116              if success then return ()
1117                         else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1118
1119 -----------------------------------------------------------------------------
1120 -- Making a DLL (only for Win32)
1121
1122 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1123 doMkDLL dflags o_files dep_packages = do
1124     let verb = getVerbFlag dflags
1125     static     <- readIORef v_Static
1126     no_hs_main <- readIORef v_NoHsMain
1127
1128     o_file <- readIORef v_Output_file
1129     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1130
1131     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1132     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1133
1134     lib_paths <- readIORef v_Library_paths
1135     let lib_path_opts = map ("-L"++) lib_paths
1136
1137     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1138
1139         -- probably _stub.o files
1140     extra_ld_inputs <- readIORef v_Ld_inputs
1141
1142         -- opts from -optdll-<blah>
1143     extra_ld_opts <- getStaticOpts v_Opt_dll
1144
1145     let pstate = pkgState dflags
1146         rts_id | Just id <- rtsPackageId pstate = id
1147                | otherwise = panic "staticLink: rts package missing"
1148         base_id | Just id <- basePackageId pstate = id
1149                 | otherwise = panic "staticLink: base package missing"
1150         rts_pkg  = getPackageDetails pstate rts_id
1151         base_pkg = getPackageDetails pstate base_id
1152
1153     let extra_os = if static || no_hs_main
1154                    then []
1155                    else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1156                           head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1157
1158     (md_c_flags, _) <- machdepCCOpts dflags
1159     SysTools.runMkDLL dflags
1160          ([ SysTools.Option verb
1161           , SysTools.Option "-o"
1162           , SysTools.FileOption "" output_fn
1163           ]
1164          ++ map SysTools.Option (
1165             md_c_flags
1166          ++ o_files
1167          ++ extra_os
1168          ++ [ "--target=i386-mingw32" ]
1169          ++ extra_ld_inputs
1170          ++ lib_path_opts
1171          ++ extra_ld_opts
1172          ++ pkg_lib_path_opts
1173          ++ pkg_link_opts
1174          ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1175                then [ "" ]
1176                else [ "--export-all" ])
1177         ))
1178
1179 -- -----------------------------------------------------------------------------
1180 -- Misc.
1181
1182 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1183 doCpp dflags raw include_cc_opts input_fn output_fn = do
1184     let hscpp_opts = getOpts dflags opt_P
1185
1186     cmdline_include_paths <- readIORef v_Include_paths
1187
1188     pkg_include_dirs <- getPackageIncludePath dflags []
1189     let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1190                           (cmdline_include_paths ++ pkg_include_dirs)
1191
1192     let verb = getVerbFlag dflags
1193
1194     cc_opts <- if not include_cc_opts 
1195                   then return []
1196                   else do let optc = getOpts dflags opt_c
1197                           (md_c_flags, _) <- machdepCCOpts dflags
1198                           return (optc ++ md_c_flags)
1199
1200     let cpp_prog args | raw       = SysTools.runCpp dflags args
1201                       | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1202
1203     let target_defs = 
1204           [ "-D" ++ cTARGETOS   ++ "_TARGET_OS=1",
1205             "-D" ++ cTARGETARCH ++ "_TARGET_ARCH=1" ]
1206
1207     cpp_prog       ([SysTools.Option verb]
1208                     ++ map SysTools.Option include_paths
1209                     ++ map SysTools.Option hsSourceCppOpts
1210                     ++ map SysTools.Option hscpp_opts
1211                     ++ map SysTools.Option cc_opts
1212                     ++ map SysTools.Option target_defs
1213                     ++ [ SysTools.Option     "-x"
1214                        , SysTools.Option     "c"
1215                        , SysTools.Option     input_fn
1216         -- We hackily use Option instead of FileOption here, so that the file
1217         -- name is not back-slashed on Windows.  cpp is capable of
1218         -- dealing with / in filenames, so it works fine.  Furthermore
1219         -- if we put in backslashes, cpp outputs #line directives
1220         -- with *double* backslashes.   And that in turn means that
1221         -- our error messages get double backslashes in them.
1222         -- In due course we should arrange that the lexer deals
1223         -- with these \\ escapes properly.
1224                        , SysTools.Option     "-o"
1225                        , SysTools.FileOption "" output_fn
1226                        ])
1227
1228 -- -----------------------------------------------------------------------------
1229 -- Misc.
1230
1231 hscNextPhase :: HscLang -> IO Phase
1232 hscNextPhase hsc_lang = do
1233   split <- readIORef v_Split_object_files
1234   return (case hsc_lang of
1235                 HscC -> HCc
1236                 HscAsm | split -> SplitMangle
1237                        | otherwise -> As
1238                 HscNothing     -> HCc  -- dummy (no output will be generated)
1239                 HscInterpreted -> HCc  -- "" ""
1240                 _other         -> HCc  -- "" ""
1241         )
1242
1243 hscMaybeAdjustLang :: HscLang -> IO HscLang
1244 hscMaybeAdjustLang current_hsc_lang = do
1245   todo    <- readIORef v_GhcMode
1246   keep_hc <- readIORef v_Keep_hc_files
1247   let hsc_lang
1248         -- don't change the lang if we're interpreting
1249          | current_hsc_lang == HscInterpreted = current_hsc_lang
1250         -- force -fvia-C if we are being asked for a .hc file
1251          | todo == StopBefore HCc  || keep_hc = HscC
1252         -- otherwise, stick to the plan
1253          | otherwise = current_hsc_lang
1254   return hsc_lang