1 -----------------------------------------------------------------------------
5 -- (c) The University of Glasgow 2005
7 -----------------------------------------------------------------------------
9 module DriverPipeline (
10 -- Run a series of compilation steps in a pipeline, for a
11 -- collection of source files.
14 -- Interfaces for the batch-mode driver
17 -- Interfaces for the compilation manager (interpreted/batch-mode)
19 compile, CompResult(..),
27 #include "HsVersions.h"
32 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
33 import qualified SysTools
41 import StaticFlags ( v_Ld_inputs, opt_Static, WayName(..) )
45 import StringBuffer ( hGetStringBuffer )
46 import BasicTypes ( SuccessFlag(..) )
47 import Maybes ( expectJust )
48 import ParserCoreUtils ( getCoreModuleName )
49 import SrcLoc ( unLoc )
50 import SrcLoc ( Located(..) )
53 import DATA_IOREF ( readIORef, writeIORef, IORef )
54 import GLAEXTS ( Int(..) )
60 import Data.List ( isSuffixOf )
64 -- ---------------------------------------------------------------------------
67 -- Just preprocess a file, put the result in a temp. file (used by the
68 -- compilation manager during the summary phase).
70 -- We return the augmented DynFlags, because they contain the result
71 -- of slurping in the OPTIONS pragmas
73 preprocess :: DynFlags -> (FilePath, Maybe Phase) -> IO (DynFlags, FilePath)
74 preprocess dflags (filename, mb_phase) =
75 ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename)
76 runPipeline anyHsc dflags (filename, mb_phase) Temporary Nothing{-no ModLocation-}
78 -- ---------------------------------------------------------------------------
81 -- Compile a single module, under the control of the compilation manager.
83 -- This is the interface between the compilation manager and the
84 -- compiler proper (hsc), where we deal with tedious details like
85 -- reading the OPTIONS pragma from the source file, and passing the
86 -- output of hsc through the C compiler.
88 -- NB. No old interface can also mean that the source has changed.
92 -> Maybe Linkable -- Just linkable <=> source unchanged
93 -> Maybe ModIface -- Old interface, if available
98 = CompOK ModDetails -- New details
100 (Maybe Linkable) -- a Maybe, for the same reasons as hm_linkable
105 compile hsc_env mod_summary maybe_old_linkable old_iface mod_index nmods = do
107 let dflags0 = ms_hspp_opts mod_summary
108 this_mod = ms_mod mod_summary
109 src_flavour = ms_hsc_src mod_summary
112 | Just l <- maybe_old_linkable, isObjectLinkable l = True
115 showPass dflags0 ("Compiling " ++ showModMsg have_object mod_summary)
117 let location = ms_location mod_summary
118 let input_fn = expectJust "compile:hs" (ml_hs_file location)
119 let input_fnpp = ms_hspp_file mod_summary
121 debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
123 let (basename, _) = splitFilename input_fn
125 -- We add the directory in which the .hs files resides) to the import path.
126 -- This is needed when we try to compile the .hc file later, if it
127 -- imports a _stub.h file that we created here.
128 let current_dir = directoryOf basename
129 old_paths = includePaths dflags0
130 dflags = dflags0 { includePaths = current_dir : old_paths }
132 -- Figure out what lang we're generating
133 let hsc_lang = hscTarget dflags
134 -- ... and what the next phase should be
135 let next_phase = hscNextPhase dflags src_flavour hsc_lang
136 -- ... and what file to generate the output into
137 output_fn <- getOutputFilename dflags next_phase
138 Temporary basename next_phase (Just location)
140 let dflags' = dflags { hscTarget = hsc_lang,
141 hscOutName = output_fn,
142 extCoreName = basename ++ ".hcr" }
144 -- -no-recomp should also work with --make
145 let do_recomp = dopt Opt_RecompChecking dflags
146 source_unchanged = isJust maybe_old_linkable && do_recomp
147 hsc_env' = hsc_env { hsc_dflags = dflags' }
148 object_filename = ml_obj_file location
150 let getStubLinkable False = return []
152 = do stub_o <- compileStub dflags' this_mod location
153 return [ DotO stub_o ]
155 handleBatch (HscNoRecomp, iface, details)
156 = ASSERT (isJust maybe_old_linkable)
157 return (CompOK details iface maybe_old_linkable)
158 handleBatch (HscRecomp hasStub, iface, details)
159 | isHsBoot src_flavour
160 = return (CompOK details iface Nothing)
162 = do stub_unlinked <- getStubLinkable hasStub
163 (hs_unlinked, unlinked_time) <-
166 -> return ([], ms_hs_date mod_summary)
167 -- We're in --make mode: finish the compilation pipeline.
169 -> do runPipeline StopLn dflags (output_fn,Nothing) Persistent
171 -- The object filename comes from the ModLocation
172 o_time <- getModificationTime object_filename
173 return ([DotO object_filename], o_time)
174 let linkable = LM unlinked_time this_mod
175 (hs_unlinked ++ stub_unlinked)
176 return (CompOK details iface (Just linkable))
178 handleInterpreted (InteractiveNoRecomp, iface, details)
179 = ASSERT (isJust maybe_old_linkable)
180 return (CompOK details iface maybe_old_linkable)
181 handleInterpreted (InteractiveRecomp hasStub comp_bc, iface, details)
182 = do stub_unlinked <- getStubLinkable hasStub
183 let hs_unlinked = [BCOs comp_bc]
184 unlinked_time = ms_hs_date mod_summary
185 -- Why do we use the timestamp of the source file here,
186 -- rather than the current time? This works better in
187 -- the case where the local clock is out of sync
188 -- with the filesystem's clock. It's just as accurate:
189 -- if the source is modified, then the linkable will
191 let linkable = LM unlinked_time this_mod
192 (hs_unlinked ++ stub_unlinked)
193 return (CompOK details iface (Just linkable))
195 let runCompiler compiler handle
196 = do mbResult <- compiler hsc_env' mod_summary
197 source_unchanged old_iface
198 (Just (mod_index, nmods))
200 Nothing -> return CompErrs
201 Just result -> handle result
204 HscInterpreted | not (isHsBoot src_flavour) -- We can't compile boot files to
205 -- bytecode so don't even try.
206 -> runCompiler hscCompileInteractive handleInterpreted
208 -> runCompiler hscCompileBatch handleBatch
210 -----------------------------------------------------------------------------
211 -- stub .h and .c files (for foreign export support)
213 -- The _stub.c file is derived from the haskell source file, possibly taking
214 -- into account the -stubdir option.
216 -- Consequently, we derive the _stub.o filename from the haskell object
219 -- This isn't necessarily the same as the object filename we
220 -- would get if we just compiled the _stub.c file using the pipeline.
223 -- ghc src/A.hs -odir obj
225 -- results in obj/A.o, and src/A_stub.c. If we compile src/A_stub.c with
226 -- -odir obj, we would get obj/src/A_stub.o, which is wrong; we want
229 compileStub :: DynFlags -> Module -> ModLocation -> IO FilePath
230 compileStub dflags mod location = do
231 let (o_base, o_ext) = splitFilename (ml_obj_file location)
232 stub_o = o_base ++ "_stub" `joinFileExt` o_ext
234 -- compile the _stub.c file w/ gcc
235 let (stub_c,_) = mkStubPaths dflags mod location
236 runPipeline StopLn dflags (stub_c,Nothing)
237 (SpecificFile stub_o) Nothing{-no ModLocation-}
242 -- ---------------------------------------------------------------------------
245 link :: GhcMode -- interactive or batch
246 -> DynFlags -- dynamic flags
247 -> Bool -- attempt linking in batch mode?
248 -> HomePackageTable -- what to link
251 -- For the moment, in the batch linker, we don't bother to tell doLink
252 -- which packages to link -- it just tries all that are available.
253 -- batch_attempt_linking should only be *looked at* in batch mode. It
254 -- should only be True if the upsweep was successful and someone
255 -- exports main, i.e., we have good reason to believe that linking
259 link Interactive dflags batch_attempt_linking hpt
260 = do -- Not Linking...(demand linker will do the job)
264 link JustTypecheck dflags batch_attempt_linking hpt
267 link BatchCompile dflags batch_attempt_linking hpt
268 | batch_attempt_linking
271 home_mod_infos = moduleEnvElts hpt
273 -- the packages we depend on
274 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
276 -- the linkables to link
277 linkables = map (expectJust "link".hm_linkable) home_mod_infos
279 debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
281 -- check for the -no-link flag
282 if isNoLink (ghcLink dflags)
283 then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
287 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
288 obj_files = concatMap getOfiles linkables
290 exe_file = exeFileName dflags
292 -- if the modification time on the executable is later than the
293 -- modification times on all of the objects, then omit linking
294 -- (unless the -no-recomp flag was given).
295 e_exe_time <- IO.try $ getModificationTime exe_file
297 | Left _ <- e_exe_time = True
298 | Right t <- e_exe_time =
299 any (t <) (map linkableTime linkables)
301 if dopt Opt_RecompChecking dflags && not linking_needed
302 then do debugTraceMsg dflags 1 (text exe_file <+> ptext SLIT("is up to date, linking not required."))
306 debugTraceMsg dflags 1 (ptext SLIT("Linking") <+> text exe_file
309 -- Don't showPass in Batch mode; doLink will do that for us.
310 let link = case ghcLink dflags of
312 StaticLink -> staticLink
313 link dflags obj_files pkg_deps
315 debugTraceMsg dflags 3 (text "link: done")
317 -- staticLink only returns if it succeeds
321 = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
322 text " Main.main not exported; not linking.")
326 -- -----------------------------------------------------------------------------
327 -- Compile files in one-shot mode.
329 oneShot :: DynFlags -> Phase -> [(String, Maybe Phase)] -> IO ()
330 oneShot dflags stop_phase srcs = do
331 o_files <- mapM (compileFile dflags stop_phase) srcs
332 doLink dflags stop_phase o_files
334 compileFile :: DynFlags -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
335 compileFile dflags stop_phase (src, mb_phase) = do
336 exists <- doesFileExist src
338 throwDyn (CmdLineError ("does not exist: " ++ src))
341 split = dopt Opt_SplitObjs dflags
342 mb_o_file = outputFile dflags
343 ghc_link = ghcLink dflags -- Set by -c or -no-link
345 -- When linking, the -o argument refers to the linker's output.
346 -- otherwise, we use it as the name for the pipeline's output.
348 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
349 -- -o foo applies to linker
350 | Just o_file <- mb_o_file = SpecificFile o_file
351 -- -o foo applies to the file we are compiling now
352 | otherwise = Persistent
354 stop_phase' = case stop_phase of
355 As | split -> SplitAs
358 (_, out_file) <- runPipeline stop_phase' dflags
359 (src, mb_phase) output Nothing{-no ModLocation-}
363 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
364 doLink dflags stop_phase o_files
365 | not (isStopLn stop_phase)
366 = return () -- We stopped before the linking phase
369 = case ghcLink dflags of
371 StaticLink -> staticLink dflags o_files link_pkgs
372 MkDLL -> doMkDLL dflags o_files link_pkgs
374 -- Always link in the haskell98 package for static linking. Other
375 -- packages have to be specified via the -package flag.
377 | ExtPackage h98_id <- haskell98PackageId (pkgState dflags) = [h98_id]
381 -- ---------------------------------------------------------------------------
382 -- Run a compilation pipeline, consisting of multiple phases.
384 -- This is the interface to the compilation pipeline, which runs
385 -- a series of compilation steps on a single source file, specifying
386 -- at which stage to stop.
388 -- The DynFlags can be modified by phases in the pipeline (eg. by
389 -- GHC_OPTIONS pragmas), and the changes affect later phases in the
394 -- output should be to a temporary file: we're going to
395 -- run more compilation steps on this output later
397 -- we want a persistent file, i.e. a file in the current directory
398 -- derived from the input filename, but with the appropriate extension.
399 -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
400 | SpecificFile FilePath
401 -- the output must go into the specified file.
404 :: Phase -- When to stop
405 -> DynFlags -- Dynamic flags
406 -> (FilePath,Maybe Phase) -- Input filename (and maybe -x suffix)
407 -> PipelineOutput -- Output filename
408 -> Maybe ModLocation -- A ModLocation, if this is a Haskell module
409 -> IO (DynFlags, FilePath) -- (final flags, output filename)
411 runPipeline stop_phase dflags (input_fn, mb_phase) output maybe_loc
413 let (basename, suffix) = splitFilename input_fn
415 -- If we were given a -x flag, then use that phase to start from
417 | Just x_phase <- mb_phase = x_phase
418 | otherwise = startPhase suffix
420 -- We want to catch cases of "you can't get there from here" before
421 -- we start the pipeline, because otherwise it will just run off the
424 -- There is a partial ordering on phases, where A < B iff A occurs
425 -- before B in a normal compilation pipeline.
427 when (not (start_phase `happensBefore` stop_phase)) $
429 ("cannot compile this file to desired target: "
432 -- this is a function which will be used to calculate output file names
433 -- as we go along (we partially apply it to some of its inputs here)
434 let get_output_fn = getOutputFilename dflags stop_phase output basename
436 -- Execute the pipeline...
437 (dflags', output_fn, maybe_loc) <-
438 pipeLoop dflags start_phase stop_phase input_fn
439 basename suffix get_output_fn maybe_loc
441 -- Sometimes, a compilation phase doesn't actually generate any output
442 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
443 -- stage, but we wanted to keep the output, then we have to explicitly
447 return (dflags', output_fn)
449 do final_fn <- get_output_fn stop_phase maybe_loc
450 when (final_fn /= output_fn) $
451 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
452 ++ "'") output_fn final_fn
453 return (dflags', final_fn)
457 pipeLoop :: DynFlags -> Phase -> Phase
458 -> FilePath -> String -> Suffix
459 -> (Phase -> Maybe ModLocation -> IO FilePath)
461 -> IO (DynFlags, FilePath, Maybe ModLocation)
463 pipeLoop dflags phase stop_phase
464 input_fn orig_basename orig_suff
465 orig_get_output_fn maybe_loc
467 | phase `eqPhase` stop_phase -- All done
468 = return (dflags, input_fn, maybe_loc)
470 | not (phase `happensBefore` stop_phase)
471 -- Something has gone wrong. We'll try to cover all the cases when
472 -- this could happen, so if we reach here it is a panic.
473 -- eg. it might happen if the -C flag is used on a source file that
474 -- has {-# OPTIONS -fasm #-}.
475 = panic ("pipeLoop: at phase " ++ show phase ++
476 " but I wanted to stop at phase " ++ show stop_phase)
479 = do { (next_phase, dflags', maybe_loc, output_fn)
480 <- runPhase phase stop_phase dflags orig_basename
481 orig_suff input_fn orig_get_output_fn maybe_loc
482 ; pipeLoop dflags' next_phase stop_phase output_fn
483 orig_basename orig_suff orig_get_output_fn maybe_loc }
486 :: DynFlags -> Phase -> PipelineOutput -> String
487 -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
488 getOutputFilename dflags stop_phase output basename
492 odir = objectDir dflags
493 osuf = objectSuf dflags
494 keep_hc = dopt Opt_KeepHcFiles dflags
495 keep_raw_s = dopt Opt_KeepRawSFiles dflags
496 keep_s = dopt Opt_KeepSFiles dflags
498 myPhaseInputExt HCc = hcsuf
499 myPhaseInputExt StopLn = osuf
500 myPhaseInputExt other = phaseInputExt other
502 func next_phase maybe_location
503 | is_last_phase, Persistent <- output = persistent_fn
504 | is_last_phase, SpecificFile f <- output = return f
505 | keep_this_output = persistent_fn
506 | otherwise = newTempName dflags suffix
508 is_last_phase = next_phase `eqPhase` stop_phase
510 -- sometimes, we keep output from intermediate stages
514 Mangle | keep_raw_s -> True
516 HCc | keep_hc -> True
519 suffix = myPhaseInputExt next_phase
521 -- persistent object files get put in odir
523 | StopLn <- next_phase = return odir_persistent
524 | otherwise = return persistent
526 persistent = basename `joinFileExt` suffix
529 | Just loc <- maybe_location = ml_obj_file loc
530 | Just d <- odir = d `joinFileName` persistent
531 | otherwise = persistent
534 -- -----------------------------------------------------------------------------
535 -- Each phase in the pipeline returns the next phase to execute, and the
536 -- name of the file in which the output was placed.
538 -- We must do things dynamically this way, because we often don't know
539 -- what the rest of the phases will be until part-way through the
540 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
541 -- of a source file can change the latter stages of the pipeline from
542 -- taking the via-C route to using the native code generator.
544 runPhase :: Phase -- Do this phase first
545 -> Phase -- Stop just before this phase
547 -> String -- basename of original input source
548 -> String -- its extension
549 -> FilePath -- name of file which contains the input to this phase.
550 -> (Phase -> Maybe ModLocation -> IO FilePath)
551 -- how to calculate the output filename
552 -> Maybe ModLocation -- the ModLocation, if we have one
553 -> IO (Phase, -- next phase
554 DynFlags, -- new dynamic flags
555 Maybe ModLocation, -- the ModLocation, if we have one
556 FilePath) -- output filename
558 -- Invariant: the output filename always contains the output
559 -- Interesting case: Hsc when there is no recompilation to do
560 -- Then the output filename is still a .o file
562 -------------------------------------------------------------------------------
565 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
566 = do let unlit_flags = getOpts dflags opt_L
567 -- The -h option passes the file name for unlit to put in a #line directive
568 output_fn <- get_output_fn (Cpp sf) maybe_loc
570 SysTools.runUnlit dflags
571 (map SysTools.Option unlit_flags ++
572 [ SysTools.Option "-h"
573 , SysTools.Option input_fn
574 , SysTools.FileOption "" input_fn
575 , SysTools.FileOption "" output_fn
578 return (Cpp sf, dflags, maybe_loc, output_fn)
580 -------------------------------------------------------------------------------
581 -- Cpp phase : (a) gets OPTIONS out of file
582 -- (b) runs cpp if necessary
584 runPhase (Cpp sf) _stop dflags0 basename suff input_fn get_output_fn maybe_loc
585 = do src_opts <- getOptionsFromFile input_fn
586 (dflags,unhandled_flags) <- parseDynamicFlags dflags0 (map unLoc src_opts)
587 checkProcessArgsResult unhandled_flags (basename `joinFileExt` suff)
589 if not (dopt Opt_Cpp dflags) then
590 -- no need to preprocess CPP, just pass input file along
591 -- to the next phase of the pipeline.
592 return (HsPp sf, dflags, maybe_loc, input_fn)
594 output_fn <- get_output_fn (HsPp sf) maybe_loc
595 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
596 return (HsPp sf, dflags, maybe_loc, output_fn)
598 -------------------------------------------------------------------------------
601 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
602 = do if not (dopt Opt_Pp dflags) then
603 -- no need to preprocess, just pass input file along
604 -- to the next phase of the pipeline.
605 return (Hsc sf, dflags, maybe_loc, input_fn)
607 let hspp_opts = getOpts dflags opt_F
608 let orig_fn = basename `joinFileExt` suff
609 output_fn <- get_output_fn (Hsc sf) maybe_loc
610 SysTools.runPp dflags
611 ( [ SysTools.Option orig_fn
612 , SysTools.Option input_fn
613 , SysTools.FileOption "" output_fn
615 map SysTools.Option hspp_opts
617 return (Hsc sf, dflags, maybe_loc, output_fn)
619 -----------------------------------------------------------------------------
622 -- Compilation of a single module, in "legacy" mode (_not_ under
623 -- the direction of the compilation manager).
624 runPhase (Hsc src_flavour) stop dflags0 basename suff input_fn get_output_fn _maybe_loc
625 = do -- normal Hsc mode, not mkdependHS
627 -- we add the current directory (i.e. the directory in which
628 -- the .hs files resides) to the import path, since this is
629 -- what gcc does, and it's probably what you want.
630 let current_dir = directoryOf basename
632 paths = includePaths dflags0
633 dflags = dflags0 { includePaths = current_dir : paths }
635 -- gather the imports and module name
636 (hspp_buf,mod_name) <-
638 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
639 ; m <- getCoreModuleName input_fn
640 ; return (Nothing, mkModule m) }
642 other -> do { buf <- hGetStringBuffer input_fn
643 ; (_,_,L _ mod_name) <- getImports dflags buf input_fn
644 ; return (Just buf, mod_name) }
646 -- Build a ModLocation to pass to hscMain.
647 -- The source filename is rather irrelevant by now, but it's used
648 -- by hscMain for messages. hscMain also needs
649 -- the .hi and .o filenames, and this is as good a way
650 -- as any to generate them, and better than most. (e.g. takes
651 -- into accout the -osuf flags)
652 location1 <- mkHomeModLocation2 dflags mod_name basename suff
654 -- Boot-ify it if necessary
655 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
656 | otherwise = location1
659 -- Take -ohi into account if present
660 -- This can't be done in mkHomeModuleLocation because
661 -- it only applies to the module being compiles
662 let ohi = outputHi dflags
663 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
664 | otherwise = location2
666 -- Take -o into account if present
667 -- Very like -ohi, but we must *only* do this if we aren't linking
668 -- (If we're linking then the -o applies to the linked thing, not to
669 -- the object file for one module.)
670 -- Note the nasty duplication with the same computation in compileFile above
671 let expl_o_file = outputFile dflags
672 location4 | Just ofile <- expl_o_file
673 , isNoLink (ghcLink dflags)
674 = location3 { ml_obj_file = ofile }
675 | otherwise = location3
677 -- Make the ModSummary to hand to hscMain
678 src_timestamp <- getModificationTime (basename `joinFileExt` suff)
680 unused_field = panic "runPhase:ModSummary field"
681 -- Some fields are not looked at by hscMain
682 mod_summary = ModSummary { ms_mod = mod_name,
683 ms_hsc_src = src_flavour,
684 ms_hspp_file = input_fn,
685 ms_hspp_opts = dflags,
686 ms_hspp_buf = hspp_buf,
687 ms_location = location4,
688 ms_hs_date = src_timestamp,
689 ms_obj_date = Nothing,
690 ms_imps = unused_field,
691 ms_srcimps = unused_field }
693 o_file = ml_obj_file location4 -- The real object file
696 -- Figure out if the source has changed, for recompilation avoidance.
698 -- Setting source_unchanged to True means that M.o seems
699 -- to be up to date wrt M.hs; so no need to recompile unless imports have
700 -- changed (which the compiler itself figures out).
701 -- Setting source_unchanged to False tells the compiler that M.o is out of
702 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
703 let do_recomp = dopt Opt_RecompChecking dflags
705 if not do_recomp || not (isStopLn stop)
706 -- Set source_unchanged to False unconditionally if
707 -- (a) recompilation checker is off, or
708 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
710 -- Otherwise look at file modification dates
711 else do o_file_exists <- doesFileExist o_file
713 then return False -- Need to recompile
714 else do t2 <- getModificationTime o_file
715 if t2 > src_timestamp
720 let hsc_lang = hscTarget dflags
721 let next_phase = hscNextPhase dflags src_flavour hsc_lang
722 output_fn <- get_output_fn next_phase (Just location4)
724 let dflags' = dflags { hscTarget = hsc_lang,
725 hscOutName = output_fn,
726 extCoreName = basename ++ ".hcr" }
728 hsc_env <- newHscEnv dflags'
730 -- Tell the finder cache about this module
731 addHomeModuleToFinder hsc_env mod_name location4
734 mbResult <- hscCompileOneShot hsc_env
735 mod_summary source_unchanged
737 Nothing -- No "module i of n" progress info
740 Nothing -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
742 -> do SysTools.touch dflags' "Touching object file" o_file
743 -- The .o file must have a later modification date
744 -- than the source file (else we wouldn't be in HscNoRecomp)
745 -- but we touch it anyway, to keep 'make' happy (we think).
746 return (StopLn, dflags', Just location4, o_file)
747 Just (HscRecomp hasStub)
749 do stub_o <- compileStub dflags' mod_name location4
750 consIORef v_Ld_inputs stub_o
751 -- In the case of hs-boot files, generate a dummy .o-boot
752 -- stamp file for the benefit of Make
753 when (isHsBoot src_flavour) $
754 SysTools.touch dflags' "Touching object file" o_file
755 return (next_phase, dflags', Just location4, output_fn)
757 -----------------------------------------------------------------------------
760 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
762 output_fn <- get_output_fn Cmm maybe_loc
763 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
764 return (Cmm, dflags, maybe_loc, output_fn)
766 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
768 let hsc_lang = hscTarget dflags
769 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
770 output_fn <- get_output_fn next_phase maybe_loc
772 let dflags' = dflags { hscTarget = hsc_lang,
773 hscOutName = output_fn,
774 extCoreName = basename ++ ".hcr" }
776 ok <- hscCmmFile dflags' input_fn
778 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
780 return (next_phase, dflags, maybe_loc, output_fn)
782 -----------------------------------------------------------------------------
785 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
786 -- way too many hacks, and I can't say I've ever used it anyway.
788 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
789 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
790 = do let cc_opts = getOpts dflags opt_c
791 hcc = cc_phase `eqPhase` HCc
793 let cmdline_include_paths = includePaths dflags
795 -- HC files have the dependent packages stamped into them
796 pkgs <- if hcc then getHCFilePackages input_fn else return []
798 -- add package include paths even if we're just compiling .c
799 -- files; this is the Value Add(TM) that using ghc instead of
801 pkg_include_dirs <- getPackageIncludePath dflags pkgs
802 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
803 (cmdline_include_paths ++ pkg_include_dirs)
805 let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
806 let pic_c_flags = picCCOpts dflags
808 let verb = getVerbFlag dflags
810 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
812 let split_objs = dopt Opt_SplitObjs dflags
813 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
816 let excessPrecision = dopt Opt_ExcessPrecision dflags
818 let cc_opt | optLevel dflags >= 2 = "-O2"
823 let mangle = dopt Opt_DoAsmMangling dflags
825 | hcc && mangle = Mangle
827 output_fn <- get_output_fn next_phase maybe_loc
832 -- on x86 the floating point regs have greater precision
833 -- than a double, which leads to unpredictable results.
834 -- By default, we turn this off with -ffloat-store unless
835 -- the user specified -fexcess-precision.
836 (if excessPrecision then [] else [ "-ffloat-store" ]) ++
838 -- gcc's -fstrict-aliasing allows two accesses to memory
839 -- to be considered non-aliasing if they have different types.
840 -- This interacts badly with the C code we generate, which is
841 -- very weakly typed, being derived from C--.
842 ["-fno-strict-aliasing"]
846 SysTools.runCc dflags (
847 -- force the C compiler to interpret this file as C when
848 -- compiling .hc files, by adding the -x c option.
849 -- Also useful for plain .c files, just in case GHC saw a
851 [ SysTools.Option "-x", SysTools.Option "c"] ++
852 [ SysTools.FileOption "" input_fn
853 , SysTools.Option "-o"
854 , SysTools.FileOption "" output_fn
856 ++ map SysTools.Option (
865 ++ [ verb, "-S", "-Wimplicit", cc_opt ]
866 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
873 return (next_phase, dflags, maybe_loc, output_fn)
875 -- ToDo: postprocess the output from gcc
877 -----------------------------------------------------------------------------
880 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
881 = do let mangler_opts = getOpts dflags opt_m
884 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
886 machdep_opts <- return []
889 let split = dopt Opt_SplitObjs dflags
891 | split = SplitMangle
893 output_fn <- get_output_fn next_phase maybe_loc
895 SysTools.runMangle dflags (map SysTools.Option mangler_opts
896 ++ [ SysTools.FileOption "" input_fn
897 , SysTools.FileOption "" output_fn
899 ++ map SysTools.Option machdep_opts)
901 return (next_phase, dflags, maybe_loc, output_fn)
903 -----------------------------------------------------------------------------
906 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
907 = do -- tmp_pfx is the prefix used for the split .s files
908 -- We also use it as the file to contain the no. of split .s files (sigh)
909 split_s_prefix <- SysTools.newTempName dflags "split"
910 let n_files_fn = split_s_prefix
912 SysTools.runSplit dflags
913 [ SysTools.FileOption "" input_fn
914 , SysTools.FileOption "" split_s_prefix
915 , SysTools.FileOption "" n_files_fn
918 -- Save the number of split files for future references
919 s <- readFile n_files_fn
920 let n_files = read s :: Int
921 writeIORef v_Split_info (split_s_prefix, n_files)
923 -- Remember to delete all these files
924 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
927 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
928 -- we don't use the filename
930 -----------------------------------------------------------------------------
933 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
934 = do let as_opts = getOpts dflags opt_a
935 let cmdline_include_paths = includePaths dflags
937 output_fn <- get_output_fn StopLn maybe_loc
939 -- we create directories for the object file, because it
940 -- might be a hierarchical module.
941 createDirectoryHierarchy (directoryOf output_fn)
943 SysTools.runAs dflags
944 (map SysTools.Option as_opts
945 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
946 ++ [ SysTools.Option "-c"
947 , SysTools.FileOption "" input_fn
948 , SysTools.Option "-o"
949 , SysTools.FileOption "" output_fn
952 return (StopLn, dflags, maybe_loc, output_fn)
955 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
957 output_fn <- get_output_fn StopLn maybe_loc
959 let (base_o, _) = splitFilename output_fn
960 split_odir = base_o ++ "_split"
961 osuf = objectSuf dflags
963 createDirectoryHierarchy split_odir
965 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
966 -- later and we don't want to pick up any old objects.
967 fs <- getDirectoryContents split_odir
968 mapM_ removeFile $ map (split_odir `joinFileName`)
969 $ filter (osuf `isSuffixOf`) fs
971 let as_opts = getOpts dflags opt_a
973 (split_s_prefix, n) <- readIORef v_Split_info
975 let split_s n = split_s_prefix ++ "__" ++ show n `joinFileExt` "s"
976 split_obj n = split_odir `joinFileName`
977 filenameOf base_o ++ "__" ++ show n
981 = SysTools.runAs dflags
982 (map SysTools.Option as_opts ++
983 [ SysTools.Option "-c"
984 , SysTools.Option "-o"
985 , SysTools.FileOption "" (split_obj n)
986 , SysTools.FileOption "" (split_s n)
989 mapM_ assemble_file [1..n]
991 -- and join the split objects into a single object file:
992 let ld_r args = SysTools.runLink dflags ([
993 SysTools.Option "-nostdlib",
994 SysTools.Option "-nodefaultlibs",
995 SysTools.Option "-Wl,-r",
996 SysTools.Option ld_x_flag,
997 SysTools.Option "-o",
998 SysTools.FileOption "" output_fn ] ++ args)
999 ld_x_flag | null cLD_X = ""
1000 | otherwise = "-Wl,-x"
1002 if cLdIsGNULd == "YES"
1004 let script = split_odir `joinFileName` "ld.script"
1006 "INPUT(" ++ unwords (map split_obj [1..n]) ++ ")"
1007 ld_r [SysTools.FileOption "" script]
1009 ld_r (map (SysTools.FileOption "" . split_obj) [1..n])
1011 return (StopLn, dflags, maybe_loc, output_fn)
1014 -----------------------------------------------------------------------------
1015 -- MoveBinary sort-of-phase
1016 -- After having produced a binary, move it somewhere else and generate a
1017 -- wrapper script calling the binary. Currently, we need this only in
1018 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1019 -- central directory.
1020 -- This is called from staticLink below, after linking. I haven't made it
1021 -- a separate phase to minimise interfering with other modules, and
1022 -- we don't need the generality of a phase (MoveBinary is always
1023 -- done after linking and makes only sense in a parallel setup) -- HWL
1025 runPhase_MoveBinary input_fn
1028 pvm_root <- getEnv "PVM_ROOT"
1029 pvm_arch <- getEnv "PVM_ARCH"
1031 pvm_executable_base = "=" ++ input_fn
1032 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1033 -- nuke old binary; maybe use configur'ed names for cp and rm?
1034 system ("rm -f " ++ pvm_executable)
1035 -- move the newly created binary into PVM land
1036 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
1037 -- generate a wrapper script for running a parallel prg under PVM
1038 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1041 -- generates a Perl skript starting a parallel prg under PVM
1042 mk_pvm_wrapper_script :: String -> String -> String -> String
1043 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1045 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1046 " if $running_under_some_shell;",
1047 "# =!=!=!=!=!=!=!=!=!=!=!",
1048 "# This script is automatically generated: DO NOT EDIT!!!",
1049 "# Generated by Glasgow Haskell Compiler",
1050 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1052 "$pvm_executable = '" ++ pvm_executable ++ "';",
1053 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1054 "$SysMan = '" ++ sysMan ++ "';",
1056 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1057 "# first, some magical shortcuts to run "commands" on the binary",
1058 "# (which is hidden)",
1059 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1060 " local($cmd) = $1;",
1061 " system("$cmd $pvm_executable");",
1062 " exit(0); # all done",
1065 "# Now, run the real binary; process the args first",
1066 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1068 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1069 "@nonPVM_args = ();",
1070 "$in_RTS_args = 0;",
1072 "args: while ($a = shift(@ARGV)) {",
1073 " if ( $a eq '+RTS' ) {",
1074 " $in_RTS_args = 1;",
1075 " } elsif ( $a eq '-RTS' ) {",
1076 " $in_RTS_args = 0;",
1078 " if ( $a eq '-d' && $in_RTS_args ) {",
1080 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1081 " $nprocessors = $1;",
1082 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1083 " $nprocessors = $1;",
1085 " push(@nonPVM_args, $a);",
1089 "local($return_val) = 0;",
1090 "# Start the parallel execution by calling SysMan",
1091 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1092 "$return_val = $?;",
1093 "# ToDo: fix race condition moving files and flushing them!!",
1094 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1095 "exit($return_val);"
1098 -----------------------------------------------------------------------------
1099 -- Complain about non-dynamic flags in OPTIONS pragmas
1101 checkProcessArgsResult flags filename
1102 = do when (notNull flags) (throwDyn (ProgramError (
1103 showSDoc (hang (text filename <> char ':')
1104 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1105 hsep (map text flags)))
1108 -----------------------------------------------------------------------------
1109 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1111 getHCFilePackages :: FilePath -> IO [PackageId]
1112 getHCFilePackages filename =
1113 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1116 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1117 return (map stringToPackageId (words rest))
1121 -----------------------------------------------------------------------------
1122 -- Static linking, of .o files
1124 -- The list of packages passed to link is the list of packages on
1125 -- which this program depends, as discovered by the compilation
1126 -- manager. It is combined with the list of packages that the user
1127 -- specifies on the command line with -package flags.
1129 -- In one-shot linking mode, we can't discover the package
1130 -- dependencies (because we haven't actually done any compilation or
1131 -- read any interface files), so the user must explicitly specify all
1134 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1135 staticLink dflags o_files dep_packages = do
1136 let verb = getVerbFlag dflags
1137 output_fn = exeFileName dflags
1139 -- get the full list of packages to link with, by combining the
1140 -- explicit packages with the auto packages and all of their
1141 -- dependencies, and eliminating duplicates.
1143 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1144 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1146 let lib_paths = libraryPaths dflags
1147 let lib_path_opts = map ("-L"++) lib_paths
1149 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1151 #ifdef darwin_TARGET_OS
1152 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1153 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1155 let framework_paths = frameworkPaths dflags
1156 framework_path_opts = map ("-F"++) framework_paths
1158 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1159 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1161 let frameworks = cmdlineFrameworks dflags
1162 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1163 -- reverse because they're added in reverse order from the cmd line
1166 -- probably _stub.o files
1167 extra_ld_inputs <- readIORef v_Ld_inputs
1169 -- opts from -optl-<blah> (including -l<blah> options)
1170 let extra_ld_opts = getOpts dflags opt_l
1172 let ways = wayNames dflags
1174 -- Here are some libs that need to be linked at the *end* of
1175 -- the command line, because they contain symbols that are referred to
1176 -- by the RTS. We can't therefore use the ordinary way opts for these.
1178 debug_opts | WayDebug `elem` ways = [
1179 #if defined(HAVE_LIBBFD)
1186 thread_opts | WayThreaded `elem` ways = [
1187 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1190 #if defined(osf3_TARGET_OS)
1196 let (md_c_flags, _) = machdepCCOpts dflags
1197 SysTools.runLink dflags (
1198 [ SysTools.Option verb
1199 , SysTools.Option "-o"
1200 , SysTools.FileOption "" output_fn
1202 ++ map SysTools.Option (
1208 #ifdef darwin_TARGET_OS
1209 ++ framework_path_opts
1212 ++ pkg_lib_path_opts
1214 #ifdef darwin_TARGET_OS
1215 ++ pkg_framework_path_opts
1216 ++ pkg_framework_opts
1222 -- parallel only: move binary to another dir -- HWL
1223 when (WayPar `elem` ways)
1224 (do success <- runPhase_MoveBinary output_fn
1225 if success then return ()
1226 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1229 exeFileName :: DynFlags -> FilePath
1231 | Just s <- outputFile dflags =
1232 #if defined(mingw32_HOST_OS)
1233 if null (suffixOf s)
1234 then s `joinFileExt` "exe"
1240 #if defined(mingw32_HOST_OS)
1246 -----------------------------------------------------------------------------
1247 -- Making a DLL (only for Win32)
1249 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1250 doMkDLL dflags o_files dep_packages = do
1251 let verb = getVerbFlag dflags
1252 let static = opt_Static
1253 let no_hs_main = dopt Opt_NoHsMain dflags
1254 let o_file = outputFile dflags
1255 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1257 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1258 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1260 let lib_paths = libraryPaths dflags
1261 let lib_path_opts = map ("-L"++) lib_paths
1263 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1265 -- probably _stub.o files
1266 extra_ld_inputs <- readIORef v_Ld_inputs
1268 -- opts from -optdll-<blah>
1269 let extra_ld_opts = getOpts dflags opt_dll
1271 let pstate = pkgState dflags
1272 rts_id | ExtPackage id <- rtsPackageId pstate = id
1273 | otherwise = panic "staticLink: rts package missing"
1274 base_id | ExtPackage id <- basePackageId pstate = id
1275 | otherwise = panic "staticLink: base package missing"
1276 rts_pkg = getPackageDetails pstate rts_id
1277 base_pkg = getPackageDetails pstate base_id
1279 let extra_os = if static || no_hs_main
1281 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1282 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1284 let (md_c_flags, _) = machdepCCOpts dflags
1285 SysTools.runMkDLL dflags
1286 ([ SysTools.Option verb
1287 , SysTools.Option "-o"
1288 , SysTools.FileOption "" output_fn
1290 ++ map SysTools.Option (
1294 ++ [ "--target=i386-mingw32" ]
1298 ++ pkg_lib_path_opts
1300 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1302 else [ "--export-all" ])
1305 -- -----------------------------------------------------------------------------
1308 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1309 doCpp dflags raw include_cc_opts input_fn output_fn = do
1310 let hscpp_opts = getOpts dflags opt_P
1311 let cmdline_include_paths = includePaths dflags
1313 pkg_include_dirs <- getPackageIncludePath dflags []
1314 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1315 (cmdline_include_paths ++ pkg_include_dirs)
1317 let verb = getVerbFlag dflags
1320 | not include_cc_opts = []
1321 | otherwise = (optc ++ md_c_flags)
1323 optc = getOpts dflags opt_c
1324 (md_c_flags, _) = machdepCCOpts dflags
1326 let cpp_prog args | raw = SysTools.runCpp dflags args
1327 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1330 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1331 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1332 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1333 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1334 -- remember, in code we *compile*, the HOST is the same our TARGET,
1335 -- and BUILD is the same as our HOST.
1337 cpp_prog ([SysTools.Option verb]
1338 ++ map SysTools.Option include_paths
1339 ++ map SysTools.Option hsSourceCppOpts
1340 ++ map SysTools.Option hscpp_opts
1341 ++ map SysTools.Option cc_opts
1342 ++ map SysTools.Option target_defs
1343 ++ [ SysTools.Option "-x"
1344 , SysTools.Option "c"
1345 , SysTools.Option input_fn
1346 -- We hackily use Option instead of FileOption here, so that the file
1347 -- name is not back-slashed on Windows. cpp is capable of
1348 -- dealing with / in filenames, so it works fine. Furthermore
1349 -- if we put in backslashes, cpp outputs #line directives
1350 -- with *double* backslashes. And that in turn means that
1351 -- our error messages get double backslashes in them.
1352 -- In due course we should arrange that the lexer deals
1353 -- with these \\ escapes properly.
1354 , SysTools.Option "-o"
1355 , SysTools.FileOption "" output_fn
1358 cHaskell1Version = "5" -- i.e., Haskell 98
1360 -- Default CPP defines in Haskell source
1362 [ "-D__HASKELL1__="++cHaskell1Version
1363 , "-D__GLASGOW_HASKELL__="++cProjectVersionInt
1365 , "-D__CONCURRENT_HASKELL__"
1369 -- -----------------------------------------------------------------------------
1372 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1373 hscNextPhase dflags HsBootFile hsc_lang = StopLn
1374 hscNextPhase dflags other hsc_lang =
1377 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1382 GLOBAL_VAR(v_Split_info, ("",0), (String,Int))
1383 -- The split prefix and number of files