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