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