Cleanup after the OPTIONS parsing was moved.
[ghc-hetmet.git] / ghc / 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    showPass dflags0 ("Compiling " ++ showModMsg have_object mod_summary)
116
117    let location   = ms_location mod_summary
118    let input_fn   = expectJust "compile:hs" (ml_hs_file location) 
119    let input_fnpp = ms_hspp_file mod_summary
120
121    debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
122
123    let (basename, _) = splitFilename input_fn
124
125   -- We add the directory in which the .hs files resides) to the import path.
126   -- This is needed when we try to compile the .hc file later, if it
127   -- imports a _stub.h file that we created here.
128    let current_dir = directoryOf basename
129        old_paths   = includePaths dflags0
130        dflags      = dflags0 { includePaths = current_dir : old_paths }
131
132    -- Figure out what lang we're generating
133    let hsc_lang = hscMaybeAdjustTarget dflags StopLn src_flavour (hscTarget dflags)
134    -- ... and what the next phase should be
135    let next_phase = hscNextPhase dflags src_flavour hsc_lang
136    -- ... and what file to generate the output into
137    output_fn <- getOutputFilename dflags next_phase 
138                         Temporary basename next_phase (Just location)
139
140    let dflags' = dflags { hscTarget = hsc_lang,
141                                 hscOutName = output_fn,
142                                 extCoreName = basename ++ ".hcr" }
143
144    -- -no-recomp should also work with --make
145    let do_recomp = dopt Opt_RecompChecking dflags
146        source_unchanged = isJust maybe_old_linkable && do_recomp
147        hsc_env' = hsc_env { hsc_dflags = dflags' }
148        object_filename = ml_obj_file location
149
150    let getStubLinkable False = return []
151        getStubLinkable True
152            = do stub_o <- compileStub dflags' this_mod location
153                 return [ DotO stub_o ]
154
155        handleBatch (HscNoRecomp, iface, details)
156            = ASSERT (isJust maybe_old_linkable)
157              return (CompOK details iface maybe_old_linkable)
158        handleBatch (HscRecomp hasStub, iface, details)
159            | isHsBoot src_flavour
160                = return (CompOK details iface Nothing)
161            | otherwise
162                = do stub_unlinked <- getStubLinkable hasStub
163                     (hs_unlinked, unlinked_time) <-
164                         case hsc_lang of
165                           HscNothing
166                             -> return ([], ms_hs_date mod_summary)
167                           -- We're in --make mode: finish the compilation pipeline.
168                           _other
169                             -> do runPipeline StopLn dflags (output_fn,Nothing) Persistent
170                                               (Just location)
171                                   -- The object filename comes from the ModLocation
172                                   o_time <- getModificationTime object_filename
173                                   return ([DotO object_filename], o_time)
174                     let linkable = LM unlinked_time this_mod
175                                    (hs_unlinked ++ stub_unlinked)
176                     return (CompOK details iface (Just linkable))
177
178        handleInterpreted (InteractiveNoRecomp, iface, details)
179            = ASSERT (isJust maybe_old_linkable)
180              return (CompOK details iface maybe_old_linkable)
181        handleInterpreted (InteractiveRecomp hasStub comp_bc, iface, details)
182            = do stub_unlinked <- getStubLinkable hasStub
183                 let hs_unlinked = [BCOs comp_bc]
184                     unlinked_time = ms_hs_date mod_summary
185                   -- Why do we use the timestamp of the source file here,
186                   -- rather than the current time?  This works better in
187                   -- the case where the local clock is out of sync
188                   -- with the filesystem's clock.  It's just as accurate:
189                   -- if the source is modified, then the linkable will
190                   -- be out of date.
191                 let linkable = LM unlinked_time this_mod
192                                (hs_unlinked ++ stub_unlinked)
193                 return (CompOK details iface (Just linkable))
194
195    let runCompiler compiler handle
196            = do mbResult <- compiler hsc_env' mod_summary
197                                      source_unchanged old_iface
198                                      (Just (mod_index, nmods))
199                 case mbResult of
200                   Nothing     -> return CompErrs
201                   Just result -> handle result
202    -- run the compiler
203    case hsc_lang of
204      HscInterpreted | not (isHsBoot src_flavour) -- We can't compile boot files to
205                                                  -- bytecode so don't even try.
206          -> runCompiler hscCompileInteractive handleInterpreted
207      HscNothing
208          -> runCompiler hscCompileNothing handleBatch
209      _other
210          -> runCompiler hscCompileBatch handleBatch
211
212 -----------------------------------------------------------------------------
213 -- stub .h and .c files (for foreign export support)
214
215 -- The _stub.c file is derived from the haskell source file, possibly taking
216 -- into account the -stubdir option.
217 --
218 -- Consequently, we derive the _stub.o filename from the haskell object
219 -- filename.  
220 --
221 -- This isn't necessarily the same as the object filename we
222 -- would get if we just compiled the _stub.c file using the pipeline.
223 -- For example:
224 --
225 --    ghc src/A.hs -odir obj
226 -- 
227 -- results in obj/A.o, and src/A_stub.c.  If we compile src/A_stub.c with
228 -- -odir obj, we would get obj/src/A_stub.o, which is wrong; we want
229 -- obj/A_stub.o.
230
231 compileStub :: DynFlags -> Module -> ModLocation -> IO FilePath
232 compileStub dflags mod location = do
233         let (o_base, o_ext) = splitFilename (ml_obj_file location)
234             stub_o = o_base ++ "_stub" `joinFileExt` o_ext
235
236         -- compile the _stub.c file w/ gcc
237         let (stub_c,_) = mkStubPaths dflags mod location
238         runPipeline StopLn dflags (stub_c,Nothing) 
239                 (SpecificFile stub_o) Nothing{-no ModLocation-}
240
241         return stub_o
242
243
244 -- ---------------------------------------------------------------------------
245 -- Link
246
247 link :: GhcMode                 -- interactive or batch
248      -> DynFlags                -- dynamic flags
249      -> Bool                    -- attempt linking in batch mode?
250      -> HomePackageTable        -- what to link
251      -> IO SuccessFlag
252
253 -- For the moment, in the batch linker, we don't bother to tell doLink
254 -- which packages to link -- it just tries all that are available.
255 -- batch_attempt_linking should only be *looked at* in batch mode.  It
256 -- should only be True if the upsweep was successful and someone
257 -- exports main, i.e., we have good reason to believe that linking
258 -- will succeed.
259
260 #ifdef GHCI
261 link Interactive dflags batch_attempt_linking hpt
262     = do -- Not Linking...(demand linker will do the job)
263          return Succeeded
264 #endif
265
266 link JustTypecheck dflags batch_attempt_linking hpt
267    = return Succeeded
268
269 link BatchCompile dflags batch_attempt_linking hpt
270    | batch_attempt_linking
271    = do 
272         let 
273             home_mod_infos = moduleEnvElts hpt
274
275             -- the packages we depend on
276             pkg_deps  = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
277
278             -- the linkables to link
279             linkables = map (expectJust "link".hm_linkable) home_mod_infos
280
281         debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
282
283         -- check for the -no-link flag
284         if isNoLink (ghcLink dflags)
285           then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
286                   return Succeeded
287           else do
288
289         let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
290             obj_files = concatMap getOfiles linkables
291
292             exe_file = exeFileName dflags
293
294         -- if the modification time on the executable is later than the
295         -- modification times on all of the objects, then omit linking
296         -- (unless the -no-recomp flag was given).
297         e_exe_time <- IO.try $ getModificationTime exe_file
298         let linking_needed 
299                 | Left _  <- e_exe_time = True
300                 | Right t <- e_exe_time = 
301                         any (t <) (map linkableTime linkables)
302
303         if dopt Opt_RecompChecking dflags && not linking_needed
304            then do debugTraceMsg dflags 1 (text exe_file <+> ptext SLIT("is up to date, linking not required."))
305                    return Succeeded
306            else do
307
308         debugTraceMsg dflags 1 (ptext SLIT("Linking") <+> text exe_file
309                                  <+> text "...")
310
311         -- Don't showPass in Batch mode; doLink will do that for us.
312         let link = case ghcLink dflags of
313                 MkDLL       -> doMkDLL
314                 StaticLink  -> staticLink
315         link dflags obj_files pkg_deps
316
317         debugTraceMsg dflags 3 (text "link: done")
318
319         -- staticLink only returns if it succeeds
320         return Succeeded
321
322    | otherwise
323    = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
324                                 text "   Main.main not exported; not linking.")
325         return Succeeded
326       
327
328 -- -----------------------------------------------------------------------------
329 -- Compile files in one-shot mode.
330
331 oneShot :: DynFlags -> Phase -> [(String, Maybe Phase)] -> IO ()
332 oneShot dflags stop_phase srcs = do
333   o_files <- mapM (compileFile dflags stop_phase) srcs
334   doLink dflags stop_phase o_files
335
336 compileFile :: DynFlags -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
337 compileFile dflags stop_phase (src, mb_phase) = do
338    exists <- doesFileExist src
339    when (not exists) $ 
340         throwDyn (CmdLineError ("does not exist: " ++ src))
341    
342    let
343         split     = dopt Opt_SplitObjs dflags
344         mb_o_file = outputFile dflags
345         ghc_link  = ghcLink dflags      -- Set by -c or -no-link
346
347         -- When linking, the -o argument refers to the linker's output. 
348         -- otherwise, we use it as the name for the pipeline's output.
349         output
350          | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
351                 -- -o foo applies to linker
352          | Just o_file <- mb_o_file = SpecificFile o_file
353                 -- -o foo applies to the file we are compiling now
354          | otherwise = Persistent
355
356         stop_phase' = case stop_phase of 
357                         As | split -> SplitAs
358                         other      -> stop_phase
359
360    (_, out_file) <- runPipeline stop_phase' dflags
361                           (src, mb_phase) output Nothing{-no ModLocation-}
362    return out_file
363
364
365 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
366 doLink dflags stop_phase o_files
367   | not (isStopLn stop_phase)
368   = return ()           -- We stopped before the linking phase
369
370   | otherwise
371   = case ghcLink dflags of
372         NoLink     -> return ()
373         StaticLink -> staticLink dflags o_files link_pkgs
374         MkDLL      -> doMkDLL dflags o_files link_pkgs
375   where
376    -- Always link in the haskell98 package for static linking.  Other
377    -- packages have to be specified via the -package flag.
378     link_pkgs
379           | ExtPackage h98_id <- haskell98PackageId (pkgState dflags) = [h98_id]
380           | otherwise = []
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 dflags 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 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          -> (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   :: DynFlags -> Phase -> PipelineOutput -> String
489   -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
490 getOutputFilename dflags stop_phase output basename
491  = func
492  where
493         hcsuf      = hcSuf dflags
494         odir       = objectDir dflags
495         osuf       = objectSuf dflags
496         keep_hc    = dopt Opt_KeepHcFiles dflags
497         keep_raw_s = dopt Opt_KeepRawSFiles dflags
498         keep_s     = dopt Opt_KeepSFiles dflags
499
500         myPhaseInputExt HCc    = hcsuf
501         myPhaseInputExt StopLn = osuf
502         myPhaseInputExt other  = phaseInputExt other
503
504         func next_phase maybe_location
505            | is_last_phase, Persistent <- output     = persistent_fn
506            | is_last_phase, SpecificFile f <- output = return f
507            | keep_this_output                        = persistent_fn
508            | otherwise                               = newTempName dflags suffix
509            where
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          -> (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 (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 (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 (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, mkModule 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   -- Make the ModSummary to hand to hscMain
680         src_timestamp <- getModificationTime (basename `joinFileExt` suff)
681         let
682             unused_field = panic "runPhase:ModSummary field"
683                 -- Some fields are not looked at by hscMain
684             mod_summary = ModSummary {  ms_mod       = mod_name, 
685                                         ms_hsc_src   = src_flavour,
686                                         ms_hspp_file = input_fn,
687                                         ms_hspp_opts = dflags,
688                                         ms_hspp_buf  = hspp_buf,
689                                         ms_location  = location4,
690                                         ms_hs_date   = src_timestamp,
691                                         ms_obj_date  = Nothing,
692                                         ms_imps      = unused_field,
693                                         ms_srcimps   = unused_field }
694
695             o_file = ml_obj_file location4      -- The real object file
696
697
698   -- Figure out if the source has changed, for recompilation avoidance.
699   --
700   -- Setting source_unchanged to True means that M.o seems
701   -- to be up to date wrt M.hs; so no need to recompile unless imports have
702   -- changed (which the compiler itself figures out).
703   -- Setting source_unchanged to False tells the compiler that M.o is out of
704   -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
705         let do_recomp = dopt Opt_RecompChecking dflags
706         source_unchanged <- 
707           if not do_recomp || not (isStopLn stop)
708                 -- Set source_unchanged to False unconditionally if
709                 --      (a) recompilation checker is off, or
710                 --      (b) we aren't going all the way to .o file (e.g. ghc -S)
711              then return False  
712                 -- Otherwise look at file modification dates
713              else do o_file_exists <- doesFileExist o_file
714                      if not o_file_exists
715                         then return False       -- Need to recompile
716                         else do t2 <- getModificationTime o_file
717                                 if t2 > src_timestamp
718                                   then return True
719                                   else return False
720
721   -- get the DynFlags
722         let hsc_lang = hscMaybeAdjustTarget dflags stop src_flavour (hscTarget dflags)
723         let next_phase = hscNextPhase dflags src_flavour hsc_lang
724         output_fn  <- get_output_fn next_phase (Just location4)
725
726         let dflags' = dflags { hscTarget = hsc_lang,
727                                hscOutName = output_fn,
728                                extCoreName = basename ++ ".hcr" }
729
730         hsc_env <- newHscEnv dflags'
731
732   -- Tell the finder cache about this module
733         addHomeModuleToFinder hsc_env mod_name location4
734
735   -- run the compiler!
736         mbResult <- hscCompileOneShot hsc_env
737                           mod_summary source_unchanged 
738                           Nothing       -- No iface
739                           Nothing       -- No "module i of n" progress info
740
741         case mbResult of
742           Nothing -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
743           Just HscNoRecomp
744               -> do SysTools.touch dflags' "Touching object file" o_file
745                     -- The .o file must have a later modification date
746                     -- than the source file (else we wouldn't be in HscNoRecomp)
747                     -- but we touch it anyway, to keep 'make' happy (we think).
748                     return (StopLn, dflags', Just location4, o_file)
749           Just (HscRecomp hasStub)
750               -> do when hasStub $
751                          do stub_o <- compileStub dflags' mod_name location4
752                             consIORef v_Ld_inputs stub_o
753                     -- In the case of hs-boot files, generate a dummy .o-boot 
754                     -- stamp file for the benefit of Make
755                     when (isHsBoot src_flavour) $
756                       SysTools.touch dflags' "Touching object file" o_file
757                     return (next_phase, dflags', Just location4, output_fn)
758
759 -----------------------------------------------------------------------------
760 -- Cmm phase
761
762 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
763   = do
764        output_fn <- get_output_fn Cmm maybe_loc
765        doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn 
766        return (Cmm, dflags, maybe_loc, output_fn)
767
768 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
769   = do
770         let hsc_lang = hscMaybeAdjustTarget dflags stop HsSrcFile (hscTarget dflags)
771         let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
772         output_fn <- get_output_fn next_phase maybe_loc
773
774         let dflags' = dflags { hscTarget = hsc_lang,
775                                hscOutName = output_fn,
776                                extCoreName = basename ++ ".hcr" }
777
778         ok <- hscCmmFile dflags' input_fn
779
780         when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
781
782         return (next_phase, dflags, maybe_loc, output_fn)
783
784 -----------------------------------------------------------------------------
785 -- Cc phase
786
787 -- we don't support preprocessing .c files (with -E) now.  Doing so introduces
788 -- way too many hacks, and I can't say I've ever used it anyway.
789
790 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
791    | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
792    = do let cc_opts = getOpts dflags opt_c
793             hcc = cc_phase `eqPhase` HCc
794
795         let cmdline_include_paths = includePaths dflags
796
797         -- HC files have the dependent packages stamped into them
798         pkgs <- if hcc then getHCFilePackages input_fn else return []
799
800         -- add package include paths even if we're just compiling .c
801         -- files; this is the Value Add(TM) that using ghc instead of
802         -- gcc gives you :)
803         pkg_include_dirs <- getPackageIncludePath dflags pkgs
804         let include_paths = foldr (\ x xs -> "-I" : x : xs) []
805                               (cmdline_include_paths ++ pkg_include_dirs)
806
807         let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
808         let pic_c_flags = picCCOpts dflags
809
810         let verb = getVerbFlag dflags
811
812         pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
813
814         let split_objs = dopt Opt_SplitObjs dflags
815             split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
816                       | otherwise         = [ ]
817
818         let excessPrecision = dopt Opt_ExcessPrecision dflags
819
820         let cc_opt | optLevel dflags >= 2 = "-O2"
821                    | otherwise            = "-O"
822
823         -- Decide next phase
824         
825         let mangle = dopt Opt_DoAsmMangling dflags
826             next_phase
827                 | hcc && mangle     = Mangle
828                 | otherwise         = As
829         output_fn <- get_output_fn next_phase maybe_loc
830
831         let
832           more_hcc_opts =
833 #if i386_TARGET_ARCH
834                 -- on x86 the floating point regs have greater precision
835                 -- than a double, which leads to unpredictable results.
836                 -- By default, we turn this off with -ffloat-store unless
837                 -- the user specified -fexcess-precision.
838                 (if excessPrecision then [] else [ "-ffloat-store" ]) ++
839 #endif
840                 -- gcc's -fstrict-aliasing allows two accesses to memory
841                 -- to be considered non-aliasing if they have different types.
842                 -- This interacts badly with the C code we generate, which is
843                 -- very weakly typed, being derived from C--.
844                 ["-fno-strict-aliasing"]
845
846
847
848         SysTools.runCc dflags (
849                 -- force the C compiler to interpret this file as C when
850                 -- compiling .hc files, by adding the -x c option.
851                 -- Also useful for plain .c files, just in case GHC saw a 
852                 -- -x c option.
853                         [ SysTools.Option "-x", SysTools.Option "c"] ++
854                         [ SysTools.FileOption "" input_fn
855                         , SysTools.Option "-o"
856                         , SysTools.FileOption "" output_fn
857                         ]
858                        ++ map SysTools.Option (
859                           md_c_flags
860                        ++ pic_c_flags
861                        ++ (if hcc && mangle
862                              then md_regd_c_flags
863                              else [])
864                        ++ (if hcc 
865                              then more_hcc_opts
866                              else [])
867                        ++ [ verb, "-S", "-Wimplicit", cc_opt ]
868                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
869                        ++ cc_opts
870                        ++ split_opt
871                        ++ include_paths
872                        ++ pkg_extra_cc_opts
873                        ))
874
875         return (next_phase, dflags, maybe_loc, output_fn)
876
877         -- ToDo: postprocess the output from gcc
878
879 -----------------------------------------------------------------------------
880 -- Mangle phase
881
882 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
883    = do let mangler_opts = getOpts dflags opt_m
884
885 #if i386_TARGET_ARCH
886         machdep_opts <- return [ show (stolen_x86_regs dflags) ]
887 #else
888         machdep_opts <- return []
889 #endif
890
891         let split = dopt Opt_SplitObjs dflags
892             next_phase
893                 | split = SplitMangle
894                 | otherwise = As
895         output_fn <- get_output_fn next_phase maybe_loc
896
897         SysTools.runMangle dflags (map SysTools.Option mangler_opts
898                           ++ [ SysTools.FileOption "" input_fn
899                              , SysTools.FileOption "" output_fn
900                              ]
901                           ++ map SysTools.Option machdep_opts)
902
903         return (next_phase, dflags, maybe_loc, output_fn)
904
905 -----------------------------------------------------------------------------
906 -- Splitting phase
907
908 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
909   = do  -- tmp_pfx is the prefix used for the split .s files
910         -- We also use it as the file to contain the no. of split .s files (sigh)
911         split_s_prefix <- SysTools.newTempName dflags "split"
912         let n_files_fn = split_s_prefix
913
914         SysTools.runSplit dflags
915                           [ SysTools.FileOption "" input_fn
916                           , SysTools.FileOption "" split_s_prefix
917                           , SysTools.FileOption "" n_files_fn
918                           ]
919
920         -- Save the number of split files for future references
921         s <- readFile n_files_fn
922         let n_files = read s :: Int
923         writeIORef v_Split_info (split_s_prefix, n_files)
924
925         -- Remember to delete all these files
926         addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
927                         | n <- [1..n_files]]
928
929         return (SplitAs, dflags, maybe_loc, "**splitmangle**")
930           -- we don't use the filename
931
932 -----------------------------------------------------------------------------
933 -- As phase
934
935 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
936   = do  let as_opts =  getOpts dflags opt_a
937         let cmdline_include_paths = includePaths dflags
938
939         output_fn <- get_output_fn StopLn maybe_loc
940
941         -- we create directories for the object file, because it
942         -- might be a hierarchical module.
943         createDirectoryHierarchy (directoryOf output_fn)
944
945         SysTools.runAs dflags   
946                        (map SysTools.Option as_opts
947                        ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
948                        ++ [ SysTools.Option "-c"
949                           , SysTools.FileOption "" input_fn
950                           , SysTools.Option "-o"
951                           , SysTools.FileOption "" output_fn
952                           ])
953
954         return (StopLn, dflags, maybe_loc, output_fn)
955
956
957 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
958   = do  
959         output_fn <- get_output_fn StopLn maybe_loc
960
961         let (base_o, _) = splitFilename output_fn
962             split_odir  = base_o ++ "_split"
963             osuf = objectSuf dflags
964
965         createDirectoryHierarchy split_odir
966
967         -- remove M_split/ *.o, because we're going to archive M_split/ *.o
968         -- later and we don't want to pick up any old objects.
969         fs <- getDirectoryContents split_odir 
970         mapM_ removeFile $ map (split_odir `joinFileName`)
971                          $ filter (osuf `isSuffixOf`) fs
972
973         let as_opts = getOpts dflags opt_a
974
975         (split_s_prefix, n) <- readIORef v_Split_info
976
977         let split_s   n = split_s_prefix ++ "__" ++ show n `joinFileExt` "s"
978             split_obj n = split_odir `joinFileName`
979                                 filenameOf base_o ++ "__" ++ show n
980                                         `joinFileExt` osuf
981
982         let assemble_file n
983               = SysTools.runAs dflags
984                          (map SysTools.Option as_opts ++
985                          [ SysTools.Option "-c"
986                          , SysTools.Option "-o"
987                          , SysTools.FileOption "" (split_obj n)
988                          , SysTools.FileOption "" (split_s n)
989                          ])
990         
991         mapM_ assemble_file [1..n]
992
993         -- and join the split objects into a single object file:
994         let ld_r args = SysTools.runLink dflags ([ 
995                                 SysTools.Option "-nostdlib",
996                                 SysTools.Option "-nodefaultlibs",
997                                 SysTools.Option "-Wl,-r", 
998                                 SysTools.Option ld_x_flag, 
999                                 SysTools.Option "-o", 
1000                                 SysTools.FileOption "" output_fn ] ++ args)
1001             ld_x_flag | null cLD_X = ""
1002                       | otherwise  = "-Wl,-x"     
1003
1004         if cLdIsGNULd == "YES"
1005             then do 
1006                   let script = split_odir `joinFileName` "ld.script"
1007                   writeFile script $
1008                       "INPUT(" ++ unwords (map split_obj [1..n]) ++ ")"
1009                   ld_r [SysTools.FileOption "" script]
1010             else do
1011                   ld_r (map (SysTools.FileOption "" . split_obj) [1..n])
1012
1013         return (StopLn, dflags, maybe_loc, output_fn)
1014
1015
1016 -----------------------------------------------------------------------------
1017 -- MoveBinary sort-of-phase
1018 -- After having produced a binary, move it somewhere else and generate a
1019 -- wrapper script calling the binary. Currently, we need this only in 
1020 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1021 -- central directory.
1022 -- This is called from staticLink below, after linking. I haven't made it
1023 -- a separate phase to minimise interfering with other modules, and
1024 -- we don't need the generality of a phase (MoveBinary is always
1025 -- done after linking and makes only sense in a parallel setup)   -- HWL
1026
1027 runPhase_MoveBinary input_fn
1028   = do  
1029         sysMan   <- getSysMan
1030         pvm_root <- getEnv "PVM_ROOT"
1031         pvm_arch <- getEnv "PVM_ARCH"
1032         let 
1033            pvm_executable_base = "=" ++ input_fn
1034            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1035         -- nuke old binary; maybe use configur'ed names for cp and rm?
1036         system ("rm -f " ++ pvm_executable)
1037         -- move the newly created binary into PVM land
1038         system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
1039         -- generate a wrapper script for running a parallel prg under PVM
1040         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1041         return True
1042
1043 -- generates a Perl skript starting a parallel prg under PVM
1044 mk_pvm_wrapper_script :: String -> String -> String -> String
1045 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1046  [
1047   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
1048   "  if $running_under_some_shell;",
1049   "# =!=!=!=!=!=!=!=!=!=!=!",
1050   "# This script is automatically generated: DO NOT EDIT!!!",
1051   "# Generated by Glasgow Haskell Compiler",
1052   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1053   "#",
1054   "$pvm_executable      = '" ++ pvm_executable ++ "';",
1055   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1056   "$SysMan = '" ++ sysMan ++ "';",
1057   "",
1058   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1059   "# first, some magical shortcuts to run "commands" on the binary",
1060   "# (which is hidden)",
1061   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1062   "    local($cmd) = $1;",
1063   "    system("$cmd $pvm_executable");",
1064   "    exit(0); # all done",
1065   "}", -}
1066   "",
1067   "# Now, run the real binary; process the args first",
1068   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
1069   "$debug = '';",
1070   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1071   "@nonPVM_args = ();",
1072   "$in_RTS_args = 0;",
1073   "",
1074   "args: while ($a = shift(@ARGV)) {",
1075   "    if ( $a eq '+RTS' ) {",
1076   "     $in_RTS_args = 1;",
1077   "    } elsif ( $a eq '-RTS' ) {",
1078   "     $in_RTS_args = 0;",
1079   "    }",
1080   "    if ( $a eq '-d' && $in_RTS_args ) {",
1081   "     $debug = '-';",
1082   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1083   "     $nprocessors = $1;",
1084   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1085   "     $nprocessors = $1;",
1086   "    } else {",
1087   "     push(@nonPVM_args, $a);",
1088   "    }",
1089   "}",
1090   "",
1091   "local($return_val) = 0;",
1092   "# Start the parallel execution by calling SysMan",
1093   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1094   "$return_val = $?;",
1095   "# ToDo: fix race condition moving files and flushing them!!",
1096   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1097   "exit($return_val);"
1098  ]
1099
1100 -----------------------------------------------------------------------------
1101 -- Complain about non-dynamic flags in OPTIONS pragmas
1102
1103 checkProcessArgsResult flags filename
1104   = do when (notNull flags) (throwDyn (ProgramError (
1105           showSDoc (hang (text filename <> char ':')
1106                       4 (text "unknown flags in  {-# OPTIONS #-} pragma:" <+>
1107                           hsep (map text flags)))
1108         )))
1109
1110 -----------------------------------------------------------------------------
1111 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1112
1113 getHCFilePackages :: FilePath -> IO [PackageId]
1114 getHCFilePackages filename =
1115   EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1116     l <- hGetLine h
1117     case l of
1118       '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1119           return (map stringToPackageId (words rest))
1120       _other ->
1121           return []
1122
1123 -----------------------------------------------------------------------------
1124 -- Static linking, of .o files
1125
1126 -- The list of packages passed to link is the list of packages on
1127 -- which this program depends, as discovered by the compilation
1128 -- manager.  It is combined with the list of packages that the user
1129 -- specifies on the command line with -package flags.  
1130 --
1131 -- In one-shot linking mode, we can't discover the package
1132 -- dependencies (because we haven't actually done any compilation or
1133 -- read any interface files), so the user must explicitly specify all
1134 -- the packages.
1135
1136 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1137 staticLink dflags o_files dep_packages = do
1138     let verb = getVerbFlag dflags
1139         output_fn = exeFileName dflags
1140
1141     -- get the full list of packages to link with, by combining the
1142     -- explicit packages with the auto packages and all of their
1143     -- dependencies, and eliminating duplicates.
1144
1145     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1146     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1147
1148     let lib_paths = libraryPaths dflags
1149     let lib_path_opts = map ("-L"++) lib_paths
1150
1151     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1152
1153 #ifdef darwin_TARGET_OS
1154     pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1155     let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1156
1157     let framework_paths = frameworkPaths dflags
1158         framework_path_opts = map ("-F"++) framework_paths
1159
1160     pkg_frameworks <- getPackageFrameworks dflags dep_packages
1161     let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1162     
1163     let frameworks = cmdlineFrameworks dflags
1164         framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1165          -- reverse because they're added in reverse order from the cmd line
1166 #endif
1167
1168         -- probably _stub.o files
1169     extra_ld_inputs <- readIORef v_Ld_inputs
1170
1171         -- opts from -optl-<blah> (including -l<blah> options)
1172     let extra_ld_opts = getOpts dflags opt_l
1173
1174     let ways = wayNames dflags
1175
1176     -- Here are some libs that need to be linked at the *end* of
1177     -- the command line, because they contain symbols that are referred to
1178     -- by the RTS.  We can't therefore use the ordinary way opts for these.
1179     let
1180         debug_opts | WayDebug `elem` ways = [ 
1181 #if defined(HAVE_LIBBFD)
1182                         "-lbfd", "-liberty"
1183 #endif
1184                          ]
1185                    | otherwise            = []
1186
1187     let
1188         thread_opts | WayThreaded `elem` ways = [ 
1189 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1190                         "-lpthread"
1191 #endif
1192 #if defined(osf3_TARGET_OS)
1193                         , "-lexc"
1194 #endif
1195                         ]
1196                     | otherwise               = []
1197
1198     let (md_c_flags, _) = machdepCCOpts dflags
1199     SysTools.runLink dflags ( 
1200                        [ SysTools.Option verb
1201                        , SysTools.Option "-o"
1202                        , SysTools.FileOption "" output_fn
1203                        ]
1204                       ++ map SysTools.Option (
1205                          md_c_flags
1206                       ++ o_files
1207                       ++ extra_ld_inputs
1208                       ++ lib_path_opts
1209                       ++ extra_ld_opts
1210 #ifdef darwin_TARGET_OS
1211                       ++ framework_path_opts
1212                       ++ framework_opts
1213 #endif
1214                       ++ pkg_lib_path_opts
1215                       ++ pkg_link_opts
1216 #ifdef darwin_TARGET_OS
1217                       ++ pkg_framework_path_opts
1218                       ++ pkg_framework_opts
1219 #endif
1220                       ++ debug_opts
1221                       ++ thread_opts
1222                     ))
1223
1224     -- parallel only: move binary to another dir -- HWL
1225     when (WayPar `elem` ways)
1226          (do success <- runPhase_MoveBinary output_fn
1227              if success then return ()
1228                         else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1229
1230
1231 exeFileName :: DynFlags -> FilePath
1232 exeFileName dflags
1233   | Just s <- outputFile dflags = 
1234 #if defined(mingw32_HOST_OS)
1235       if null (suffixOf s)
1236         then s `joinFileExt` "exe"
1237         else s
1238 #else
1239       s
1240 #endif
1241   | otherwise = 
1242 #if defined(mingw32_HOST_OS)
1243         "main.exe"
1244 #else
1245         "a.out"
1246 #endif
1247
1248 -----------------------------------------------------------------------------
1249 -- Making a DLL (only for Win32)
1250
1251 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1252 doMkDLL dflags o_files dep_packages = do
1253     let verb = getVerbFlag dflags
1254     let static = opt_Static
1255     let no_hs_main = dopt Opt_NoHsMain dflags
1256     let o_file = outputFile dflags
1257     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1258
1259     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1260     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1261
1262     let lib_paths = libraryPaths dflags
1263     let lib_path_opts = map ("-L"++) lib_paths
1264
1265     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1266
1267         -- probably _stub.o files
1268     extra_ld_inputs <- readIORef v_Ld_inputs
1269
1270         -- opts from -optdll-<blah>
1271     let extra_ld_opts = getOpts dflags opt_dll 
1272
1273     let pstate = pkgState dflags
1274         rts_id | ExtPackage id <- rtsPackageId pstate = id
1275                | otherwise = panic "staticLink: rts package missing"
1276         base_id | ExtPackage id <- basePackageId pstate = id
1277                 | otherwise = panic "staticLink: base package missing"
1278         rts_pkg  = getPackageDetails pstate rts_id
1279         base_pkg = getPackageDetails pstate base_id
1280
1281     let extra_os = if static || no_hs_main
1282                    then []
1283                    else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1284                           head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1285
1286     let (md_c_flags, _) = machdepCCOpts dflags
1287     SysTools.runMkDLL dflags
1288          ([ SysTools.Option verb
1289           , SysTools.Option "-o"
1290           , SysTools.FileOption "" output_fn
1291           ]
1292          ++ map SysTools.Option (
1293             md_c_flags
1294          ++ o_files
1295          ++ extra_os
1296          ++ [ "--target=i386-mingw32" ]
1297          ++ extra_ld_inputs
1298          ++ lib_path_opts
1299          ++ extra_ld_opts
1300          ++ pkg_lib_path_opts
1301          ++ pkg_link_opts
1302          ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1303                then [ "" ]
1304                else [ "--export-all" ])
1305         ))
1306
1307 -- -----------------------------------------------------------------------------
1308 -- Running CPP
1309
1310 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1311 doCpp dflags raw include_cc_opts input_fn output_fn = do
1312     let hscpp_opts = getOpts dflags opt_P
1313     let cmdline_include_paths = includePaths dflags
1314
1315     pkg_include_dirs <- getPackageIncludePath dflags []
1316     let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1317                           (cmdline_include_paths ++ pkg_include_dirs)
1318
1319     let verb = getVerbFlag dflags
1320
1321     let cc_opts
1322           | not include_cc_opts = []
1323           | otherwise           = (optc ++ md_c_flags)
1324                 where 
1325                       optc = getOpts dflags opt_c
1326                       (md_c_flags, _) = machdepCCOpts dflags
1327
1328     let cpp_prog args | raw       = SysTools.runCpp dflags args
1329                       | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1330
1331     let target_defs = 
1332           [ "-D" ++ HOST_OS     ++ "_BUILD_OS=1",
1333             "-D" ++ HOST_ARCH   ++ "_BUILD_ARCH=1",
1334             "-D" ++ TARGET_OS   ++ "_HOST_OS=1",
1335             "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1336         -- remember, in code we *compile*, the HOST is the same our TARGET,
1337         -- and BUILD is the same as our HOST.
1338
1339     cpp_prog       ([SysTools.Option verb]
1340                     ++ map SysTools.Option include_paths
1341                     ++ map SysTools.Option hsSourceCppOpts
1342                     ++ map SysTools.Option hscpp_opts
1343                     ++ map SysTools.Option cc_opts
1344                     ++ map SysTools.Option target_defs
1345                     ++ [ SysTools.Option     "-x"
1346                        , SysTools.Option     "c"
1347                        , SysTools.Option     input_fn
1348         -- We hackily use Option instead of FileOption here, so that the file
1349         -- name is not back-slashed on Windows.  cpp is capable of
1350         -- dealing with / in filenames, so it works fine.  Furthermore
1351         -- if we put in backslashes, cpp outputs #line directives
1352         -- with *double* backslashes.   And that in turn means that
1353         -- our error messages get double backslashes in them.
1354         -- In due course we should arrange that the lexer deals
1355         -- with these \\ escapes properly.
1356                        , SysTools.Option     "-o"
1357                        , SysTools.FileOption "" output_fn
1358                        ])
1359
1360 cHaskell1Version = "5" -- i.e., Haskell 98
1361
1362 -- Default CPP defines in Haskell source
1363 hsSourceCppOpts =
1364         [ "-D__HASKELL1__="++cHaskell1Version
1365         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
1366         , "-D__HASKELL98__"
1367         , "-D__CONCURRENT_HASKELL__"
1368         ]
1369
1370
1371 -- -----------------------------------------------------------------------------
1372 -- Misc.
1373
1374 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1375 hscNextPhase dflags HsBootFile hsc_lang  =  StopLn
1376 hscNextPhase dflags other hsc_lang = 
1377   case hsc_lang of
1378         HscC -> HCc
1379         HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1380                | otherwise -> As
1381         HscNothing     -> StopLn
1382         HscInterpreted -> StopLn
1383         _other         -> StopLn
1384
1385
1386 hscMaybeAdjustTarget :: DynFlags -> Phase -> HscSource -> HscTarget -> HscTarget
1387 hscMaybeAdjustTarget dflags stop HsBootFile current_hsc_lang 
1388   = HscNothing          -- No output (other than Foo.hi-boot) for hs-boot files
1389 hscMaybeAdjustTarget dflags stop other current_hsc_lang 
1390   = hsc_lang 
1391   where
1392         keep_hc = dopt Opt_KeepHcFiles dflags
1393         hsc_lang
1394                 -- don't change the lang if we're interpreting
1395                  | current_hsc_lang == HscInterpreted = current_hsc_lang
1396
1397                 -- force -fvia-C if we are being asked for a .hc file
1398                  | HCc <- stop = HscC
1399                  | keep_hc     = HscC
1400                 -- otherwise, stick to the plan
1401                  | otherwise = current_hsc_lang
1402
1403 GLOBAL_VAR(v_Split_info, ("",0), (String,Int))
1404         -- The split prefix and number of files