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