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