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