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