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