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