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