Ticket #1975: DriverPipeline.hs

File DriverPipeline.hs, 62.9 KB (added by maeder, 8 years ago)

that's the one from #2021

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